【发布时间】:2017-05-06 10:28:24
【问题描述】:
我使用了this 文章作为参考,但我想我搞砸了。
我想深入填充模型购物车:
var CartSchema = new Schema({
products: [{
product: { type: Schema.ObjectId, ref : 'Product' },
quantity: { type: Number, default: 1}
}],
totalItems: { type: Number, default: 0},
message: { type: String },
client: { type : Schema.ObjectId, ref : 'User' },
time: { type: Date, default: new Date()},
session: { type: String }
});
所以我得到了 product.addons 和 product.description.item
var ProductSchema = new Schema({
name: { type: String, default: '' },
inventory: { type: Number },
type: { type: String, default: 'cesta' },
price: { type: Number, required: true },
discount: { type: Number},
description: [{
item: { type : Schema.ObjectId, ref : 'Item' },
quantity: Number
}],
photos: {
photo1: String,
photo2: String
},
related_products: [{ type : Schema.ObjectId, ref : 'Product' }],
addons: [{ type : Schema.ObjectId, ref : 'Product' }],
category: { type: Schema.ObjectId, ref: 'Category' },
code: { type: String },
descricao_avulsa: String,
slug: String
});
我已经尝试过了,但它似乎一直在循环(它没有 console.log:
var populate = {
path: "products.product",
model: 'Product',
populate: [
{ path: "price name photos slug" },
{ path: "description.item addons", model: 'Item'}
]
};
Cart.findOne({session: req.cookies['express:sess']})
.populate(populate)
.exec(function(err, cart){
if(err){
return err; }
console.log(cart.products[0].product);
next();
});
我也尝试了相同的代码,其中填充变量:
var populate = [
{ path: "products.product", select: "price name photos slug description addons" },
{ path: "products.product.description.item", select: "name" },
{ path: "products.product.addons", select: "name" }
];
但这并没有得到我想要的结果。
我希望我的结果看起来像这样:
{
_id: 5859790cc307556218b9d2e1,
slug: 'nova-cestinha',
price: 14300,
addons: [ { name: 'produto' } ],
photos: {
photo1: 'https://frutacor.s3.amazonaws.com/1482258691162',
photo2: 'https://frutacor.s3.amazonaws.com/1482258691189'
},
description:
[ {
item: {name: 'casadinho'},
quantity: 4,
_id: 5859790cc307556218b9d2e4
},
{
item: {name: 'brownie},
quantity: 5,
_id: 5859790cc307556218b9d2e3 }
],
name: 'nova cestinha'
}
【问题讨论】:
标签: mongoose mongoose-populate