2017-08-16 5 views
0

Mongooseアプリケーションでは、仮想関数を使用してrefで子オブジェクトをルックアップできます。ノードMongoose仮想プロパティは、条件に一致する子を返します。

私は、2つの日付(start_date、end_date)を持つ多くの子オブジェクトに対する参照関係を持つ親オブジェクトがあるとします。

親オブジェクト:

{ 
    "id": 12345, 
    "children": [...] // <= A virtual property to the child objects below. 
} 

子は理想的には、私は現在の日付がSTART_DATEとEND_DATEの間にある子オブジェクトを返す現在と呼ばれる仮想プロパティを持っていると思い

[{ 
    "parent": 12345, 
    "start_date": "2016-01-01", 
    "end_date": "2016-02-01" 
}, 
{ 
    "parent": 12345, 
    "start_date": "2016-02-02", 
    "end_date": "2016-03-01" 
}] 

オブジェクト。今日は「2016年2月20日」である場合の例として

、私はこのように見える結果を希望:

{ 
    "id": 12345, 
    "children": [...], // <= A virtual property to the child objects below. 
    "current": { 
     "parent": 12345, 
     "start_date": "2016-02-02", 
     "end_date": "2016-03-01" 
    } 
} 

私は仮想関数内の子プロパティを見てみましたが、それそれは約束であるため、常にnullを返すようです。これを行う簡単な方法があるかどうかはわかりませんでしたが、私は本当にどんな考えにも感謝しています。

これは私が試したものですが、常にnullを返します。コンソールにログして結果が表示されても、

ParentSchema 
.virtual('current') 
.get(function() { 
    var result = null; 
    ChildModel.find({parent: this._id}, function (err, results) { 
     // ... some logic here to find the correct item. (Omitted for brevity). 
     result = foundItem; 
    }); 
    return result; 
}) 

ありがとうございました!

答えて

1

mongoose操作は非同期であるため、結果を得る前にコールバックが呼び出されるまで待つ必要があります。

ParentSchema.virtual('current').get(function() { 
    var result = null; 
    ChildModel.find({parent: this._id}, function callback(err, children) { 
     // ... 
     result = child; 
    }); 
    // by the time it reaches this point, the async function^will not yet be finished -- so result will always be null 
    return result; 
}) 

(1)仮想プロパティを使用するには、値の代わりにプロミスを返す必要があります。

ParentSchema.virtual('current').get(function() { 
    var self = this; 
    return ChildModel.find({ parent: self._id }, function (err, children) { 
     // ... 
     self.current = child; 
    }); 
}) 

次に、(2)私はそれが代わりにメソッドを使用する方が良いんだと思う

parent.current.then(function() { 
    console.log(parent.current); 
}).catch(function (err) { 
    // ... 
}) 

のようにそれを使用します。

ParentSchema.methods.getCurrent(function (callback) { 
    var self = this; 
    ChildModel.find({ parent: self._id }, function (err, children) { 
     if (err) return callback(err); 
     // ... 
     self.current = child; 
     callback(); 
    }); 
}); 

その後、

parent.getCurrent(function (err) { 
    console.log(parent.current); 
}) 
+0

優れた概要のようにそれを使用します。どうもありがとうございます! –

関連する問題