2014-04-25 111 views
0

我有一個產品模式和一個類別模式。如何根據本文檔的子文檔獲取文檔編號

var ProductSchema = new Schema({ 
    categories: [CategorySchema], 
    createdDate: { type: Date, default: Date.now }, 
}); 

var CategorySchema = new Schema({ 
    name: String, 
    createdDate: { type: Date, default: Date.now }, 
}); 

如何獲得包含特定類別的產品。如何使用mongoose.js寫這個查詢?

回答

0

假設你有一個模型定義的基礎上,ProductSchema定義Product那麼一般語法是不是從一個標準的MongoDB .find()查詢很大的不同:

var categoryId; // As whatever the desired value of the ObjectId is 

Product.find({ "categories._id": categoryId }, function(err,product) { 

    // Work with found document or err object here 

}); 

所以這只是一個簡單的「點號」查詢的形式以引用子文檔元素。

當然你的模式結構也似乎是基於embedded documents因此,這意味着你應該能夠訪問任何模式的其他屬性,以及:

Product.find({ "categories.name": "category name" }, function(err,product) { 

    // Work with found document or err object here 

}); 

對於擁有CategorySchema對象解決方案在他們自己的模型集合中,還有.poulate()方法,該方法在嵌入不實際的情況下提供了一種有效的,即使不是很有效的嵌入方法。