0
在Mongoose應用程序中,我可以使用虛擬函數通過ref查找子對象。節點Mongoose虛擬屬性返回符合條件的子項
我有一個問題是,給定一個父對象與許多具有兩個日期(start_date,end_date)的子對象的ref關係。
父對象:
{
"id": 12345,
"children": [...] // <= A virtual property to the child objects below.
}
子對象
[{
"parent": 12345,
"start_date": "2016-01-01",
"end_date": "2016-02-01"
},
{
"parent": 12345,
"start_date": "2016-02-02",
"end_date": "2016-03-01"
}]
理想情況下,我想有一個叫做當前的虛擬屬性,返回子對象在當前日期落在start_date和end_date之間。
舉個例子,如果今天是「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;
})
非常感謝!
很好的概述。非常感謝! –