我有一個orderSchema
具有subdoc productOrder
:貓鼬填充subdoc的
const paymentTrans = require('./PaymentTrans').schema;
const productOrder = require('./ProductOrder').schema;
const orderSchema = new mongoose.Schema({
orderId: { type: mongoose.Schema.Types.ObjectId },
userId : {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
productOrder: [productOrder],
totalPerOrder: {type: Number, default:''},
paymentTrans: [paymentTrans]
}, { timestamps: true });
const Order = mongoose.model('Order', orderSchema);
module.exports = Order;
porductOrder模式
const productOrderSchema = new mongoose.Schema({
sku: { type: String, default: '' },
name: { type: String, default: '' },
quantity: { type: Number, default: '' },
price: { type: Number, default: '' },
total: { type: Number, default: '' }
});
const ProductOrder = mongoose.model('ProductOrder', productOrderSchema);
module.exports = ProductOrder;
我希望得到order
productOrder
(orderSchema
):
嘗試這些
Order.findById(req.body.id)
.exec(function (err, products) {
var opts = {
path: 'productOrder',
model: 'ProductOrder'
};
Order.populate(products, opts, function (ree, products) {
console.log(JSON.stringify(products));
});
res.render('store/cart', {
title: 'MyCart',
angularApp: 'storeApp',
products: products
});
});
哪裏req.body.id
爲orderId
和console
的object
看起來像這樣:(抱歉,WebStorm
沒有複製/從控制檯粘貼)
另一種方法我試過
Order.findById(req.body.id, function (err, products) {
var opts = [
{ path: 'productOrder', model: 'ProductOrder' }
]
Order.populate(products, opts, function (err, products) {
console.log(products);
})
})
而另一個
Order.find({ _id: req.body.id, userId: req.user._id })
.populate({
path: 'productOrder',
populate: {
path: 'productOrder',
model: 'ProductOrder'
}
})
.exec(function (err, productOrder) {
//products.forEach(function(elem){
console.log("products = " + JSON.stringify(productOrder));
//});
console.log("REQ._ID " + req.body.id);
res.render('store/cart', {
title: 'MyCart',
angularApp: 'storeApp',
products: productOrder
});
});
他們都最終給我訂單的整個doc
。 我怎樣才能得到訂單的產品? (productOrder
) 感謝名單
你爲什麼不使用引用命令,並將其作爲subdoc的像你一樣的用戶做到這一點:用戶名:{類型:mongoose.Schema.Types.ObjectId,ref:'User'}? –
@IgnatGalkin,我知道這可以做到這一點...嘗試瞭解哪個更好......找不到任何東西......想法? – Jadeye