【发布时间】:2017-07-23 03:59:59
【问题描述】:
我有两个架构:配方和产品
var recipeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
products: [{
product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
productWeight: Number,
productPrice: Number
}]
})
var productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
weight: {
type: Number,
required: true
},
price: {
type: Number,
required: true
}
})
我有 addRecipe 功能
module.exports.addRecipe = function(req, res){
Recipe
.create({
name: req.body.name,
products: req.body.products
}, function(err, recipe){
if(err){
console.log("Error creating recipe");
res
.status(400)
.json(err);
} else {
console.log("Recipe created", recipe);
res
.status(201)
.json(recipe);
}
})
}
我想为数组中的每个对象计算 productPrice (productPrice = product.price * productWeight / product.Weight)。
我发布的 JSON。
{
"name": "Cake",
"products": [
{
"product": "59728a3f7765441b503e31bc",
"productWeight": 100
},
{
"product": "59728a3f7765441b503e31bd",
"productWeight": 200
},
{
"product": "59728a3f7765441b503e31be",
"productWeight": 50
},
{
"product": "59728a3f7765441b503e31bf",
"productWeight": 500
}
]
}
我还想在产品或 reicpe 编辑上更新 productPrice。 可以这样做吗?
谢谢!
【问题讨论】:
标签: node.js mongoose mongoose-populate