我無法理解貓鼬的populate方法背後的一些概念。我有一個嵌入式的方法首先工作,雖然,因爲我擔心數據和不同步的文件大量開銷我試圖改變範例ref
其他文件。貓鼬嵌套參考羣體
我的模式是類似於以下(去除不相關的屬性):
var userSchema = mongoose.Schema({
name: {type: String, default:''},
favorites:{
users:[{type: Schema.Types.ObjectId, ref: this}],
places:[{type: Schema.Types.ObjectId, ref: PlaceSchema}]
}
});
module.exports = mongoose.model('User', userSchema);
現在,我試圖讓User
的favorites
這樣的:
User.findOne({_id: currentUser}).exec(function(err, user){
console.log(user);
if (err)
throw err;
if(!user){
console.log("can't find user");
}else{ // user found
user.populate('favorites.users');
user.populate('favorites.places');
// do something to the 'user.favorites' object
}
});
雖然這並未「 t按預期工作,因爲user.favorites.users
和user.favorites.places
都未定義。
我認爲我可以像上面那樣填充,但顯然情況並非如此。從我讀到的內容來看,我一定是錯過了某些東西(可能)是ref
'ed文檔的模型?這個流程對我來說是非常新的,我有點失落。
是否有反正我可以通過填充我的查詢結果如上所示的users
和places
數組?我試過populate
與exec
鏈接,它也不起作用。有沒有更好的方法來實現這個結果?
編輯:萬一它的需要,在DB,一個User
文件顯示爲:
{
"_id": "56c36b330fbc51ba19cc83ff",
"name": "John Doe",
"favorites": {
"places": [],
"users": [
"56b9d9a45f1ada8e0c0dee27"
]
}
}
編輯:一對夫婦更多的細節......我目前存儲/刪除該引用的ObjectID這樣(注意:目標ID是一個字符串):
user.favorites.users.push({ _id: mongoose.Types.ObjectId(targetID)});
user.favorites.users.pull({ _id: mongoose.Types.ObjectId(targetID)});
另外,我需要填充users
和places
各自的文件藏漢,我認爲這可能不是很清楚我的或原始問題。
'ref'值應該是引用模型的名稱,而不是模式。 – JohnnyHK