我有一个产品列表,每个产品都有自己的选项。例如:填充另一个对象引用的对象
- 蓝色礼服(S - L)
- 红服饰(XS - S - M)
蓝色礼服和红服饰是产品,小号 ,L,XS,S和M是选项。选项模型有对产品模型的参考,我想检索所有产品,然后列出他们自己的选项。
我想用一个查询来实现它,我的问题是我从没有链接到它的选项的产品开始。所以我开始找到所有的产品,并与一个嵌套的然后与foreach循环我得到它的所有选项。然后我尝试将该选项分配给产品对象(在我的情况下,产品Ellem内部的for each),但是当我检索出它的范围当然是空的。如何填充从产品查询开始的选项?
产品架构:
var schema = new Schema({
imagePath: {type: String},
title: {type: String, required: true},
description: {type: String, required: true}
});
选项模式:
var productOptionSchema = new Schema({
type: {type: String, enum: ['grams'], default: 'grams', required: true},
value: {type: String, required: true},
price: {type: Number, required:true},
product: {type: Schema.Types.ObjectId, ref: 'User', required:true}
});
在这里,我试图寻找产品
router.get('/shop/products/list', isLoggedIn, function (req, res, next) {
Product.find()
.then(function (products) {
products.forEach(function(productElem) {
ProductOption.find({product: productElem._id})
.then(function (options) {
productElem['options'] = [];
options.forEach(function(optionElem) {
productElem['options'].push(optionElem);
});
});
});
res.render('shop/listProduct', {user:req.user, csrfToken: req.csrfToken(), messages:messages, partialCustom:
});
})
.catch(function (err) {
console.log('Error ' + err.code + ': ', err.message);
res.status(500).send('Failed to get the Product List from the DB: ' + err);
});
});
你的问题不是很清楚。请编辑该问题以使其更易于理解。 –