2015-09-06 31 views
0

所以Ive得到了我的貓鼬/ MongoDB的應用中兩個關係:MongoDB的:讓所有提及的事項,

USER:

{ 
    name: String, 
    items: [{ type: mongoose.Schema.ObjectId, ref: 'Spot' }] 
} 

和 項目

{ 
    title: String, 
    price: Number 
} 

正如你所看到的,我的用戶集合包含與項目集合有關的「多」關係。

我想知道如何得到所有項目至極在對特定用戶的項目場提及。

猜測它很常見的問題,但我不能發現的文檔或其他地方我自己的任何解決方案。有人可以幫我嗎?

回答

1

如果要存儲的用戶集合中的項目的參考,然後從用戶獲取的所有項目,它會給你的項目的對象ID的數組,然後你可以訪問他們的ID的所有項目基地

var itemIdsArray = User.items; 

    Item.find({ 
     '_id': { $in: itemIdsArray} 
    }, function(err, docs){ 
     console.log(docs); 
    }); 
0

您可以population你查詢用戶同時獲得的項目,通過使用貓鼬的支持:

User.findOne({_id: userId}).populate('items').exec(function(err, user) { 
    // user.items contains the referenced docs instead of just the ObjectIds  
}); 
相關問題