本文介绍了猫鼬填充子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有subdoc productOrder
的orderSchema
:
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
(orderSchema
)获得productOrder
:
尝试了这些
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
不能从控制台复制/粘贴)
Where req.body.id
is the orderId
and the object
in console
looks like this: (sorry, WebStorm
no Copy/Paste from console)
我尝试的另一种方式
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
)谢谢
They all end up giving me the entire doc
of the order.How can I get just the products of the order? (productOrder
)Thanx
推荐答案
您可以使用select
函数,然后按照以下说明填充
You may use select
function and then populate as following
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
});
}
});
这篇关于猫鼬填充子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!