根据populate元素计算自定义属性

时间:2017-07-22 19:31:32

标签: node.js mongoose mongoose-populate

我有两个架构:配方和产品

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。 有可能这样做吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我会为此使用virtual,但我不认为可以在不引入其他架构的情况下使用它。

var RecipeProductSchema = new mongoose.Schema({
    product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' },
    productWeight: Number
});

// note: product must be populated before calling this property
RecipeProductSchema.virtual('productPrice').get(function() {
    return this.product.price * this.productWeight / this.product.weight;
});

var RecipeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    products: [RecipeProductSchema]
})