【问题标题】:Calculate custom property based on populate element根据填充元素计算自定义属性
【发布时间】: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


    【解决方案1】:

    我会为此使用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]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多