我的orderSchema
有一个subdoc productOrder
:
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;
我希望从productOrder
(order
)获得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
object
console
中的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
的订单。
我怎样才能得到订单的产品? ({{1}})
感谢名单
答案 0 :(得分:1)
您可以使用select
功能,然后填充如下
Order.findOne({ _id: req.body.id})
.select('-_id productOrder')
.populate('productOrder')
.exec(function (err, orderObj) {
if(!err) {
var productOrder = orderObj.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
});
}
});