2017-08-16 36 views
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; 
}) 

非常感謝!

回答

1

還記得貓鼬操作是異步的,所以你需要等待他們的回調被調用之前得到結果。

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)要使用虛擬屬性,您必須返回Promise而不是值。

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

你可以這樣使用它像

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

(2)我認爲這是更好地做到使用方法來代替。

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

很好的概述。非常感謝! –