2016-03-16 84 views
0

我無法理解貓鼬的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); 

現在,我試圖讓Userfavorites這樣的:

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.usersuser.favorites.places都未定義。

我認爲我可以像上面那樣填充,但顯然情況並非如此。從我讀到的內容來看,我一定是錯過了某些東西(可能)是ref'ed文檔的模型?這個流程對我來說是非常新的,我有點失落。

是否有反正我可以通過填充我的查詢結果如上所示的usersplaces數組?我試過populateexec鏈接,它也不起作用。有沒有更好的方法來實現這個結果?

編輯:萬一它的需要,在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)}); 

另外,我需要填充usersplaces各自的文件藏漢,我認爲這可能不是很清楚我的或原始問題。

+1

'ref'值應該是引用模型的名稱,而不是模式。 – JohnnyHK

回答

0

好吧,我想通了,我需要什麼樣的支付適當的關注文檔(也有@DJeanCar的(+1)的幫助/指針)。

通過貓鼬的docs關於多個層面填充,我已經到了這個解決方案:

User.findOne({_id: currentUser}) 
    .populate({path:"favorites.users", populate: "name"}) 
    .populate({path:"favorites.places", populate: "name"}) 
    .exec(function(err, user){ 
     if(err) 
     throw err; 

     if(!user){ 
     console.log("couldnt find source user"); 
     }else{ 
     // here, user.favorites is populated and I can do what I need with the data 
     } 
    }); 

而且,從我看得出來,你也可以在populate()的選項傳遞select: "field field field",你應該需要在填充後過濾需要的文檔字段。

希望這可以幫助有類似問題的人!

1

嘗試:

User 
.findOne({_id: currentUser}) 
.populate('favorites.users') 
.populate('favorites.places') 
.exec(function (err, user) { 
    // user.favorites.users 
    // user.favorites.places 
}); 
+0

呵呵...可能是我的問題,但節點不喜歡你的'=>'語法... – Joum

+1

其ES6,編輯 – DJeanCar

+0

也許我自己解釋不夠:這工作,但我需要填充'用戶'和'地方'陣列及其各自的文件。你能指出缺少的東西嗎? – Joum