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;
})
ありがとうございました!
優れた概要のようにそれを使用します。どうもありがとうございます! –