【发布时间】:2018-03-19 02:13:32
【问题描述】:
我有一个产品列表,每个产品都有自己的选项。例如:
- 蓝色连衣裙(S - L)
- 红色连衣裙(XS - S - M)
蓝色连衣裙和红色连衣裙是产品,S、L、XS em>、S 和 M 是选项。选项模型有对产品模型的引用,我想检索所有产品然后列出他们自己的选项。
我只想通过一个查询来实现它,我的问题是我从没有链接到其选项的产品开始。因此,我开始查找所有产品,并使用带有 foreach 循环的嵌套 then 获得所有选项。然后我尝试将选项分配给产品对象(在我的情况下,forEach 中的 productElem),但是当我将其检索到范围之外时,它当然是空的。如何从产品查询开始填充选项?
产品架构:
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);
});
});
【问题讨论】:
-
你的问题不是很清楚。请编辑问题以使其更易于理解。
标签: node.js mongoose mongoose-populate