使用post hook mongoose更新另一个模式中的字段

时间:2018-02-01 20:42:29

标签: mongodb express mongoose mongoose-schema

我有那个模式:

var schema = new Schema({
number: {type: Number},
subtotal: {type: Float, required: true},
quantity: {type: Number, required: true},
prodprov: {type: Schema.Types.ObjectId, ref: 'ProdProv'},
order: {type: Schema.Types.ObjectId, ref: 'Order'}
});

module.exports = mongoose.model('OrderDetail', schema);

var schema = new Schema({
name: {type: String, required: true},
price: {type: Float, required: true},
idProvider: {type: Schema.Types.ObjectId, ref: 'Provider'},
idProduct: {type: Schema.Types.ObjectId, ref: 'Product'},
description: {type: String},
quantitySold: {type: Number}
});

module.exports = mongoose.model('ProdProv', schema);

当post.save在订单详情中发生时,我需要更新字段“quantitySold”,我试过这个:

schema.post('save', function(next){
   //But this point I can't find the prodprov to update field
})

我怎么能这样做?

谢谢。

2 个答案:

答案 0 :(得分:0)

我建议:

var ProdProv = require('./ProdProv');

var schema = new Schema({
  number: {type: Number},
  subtotal: {type: Float, required: true},
  quantity: {type: Number, required: true},
  prodprov: {type: Schema.Types.ObjectId, ref: 'ProdProv'},
  order: {type: Schema.Types.ObjectId, ref: 'Order'}
});

schema.post('save', async function(doc){
  var prod = await ProdProv.findById(doc.prodprov);
  prod.quantitySold = doc.quantity;
  prod.save()
});

module.exports = mongoose.model('OrderDetail', schema);

答案 1 :(得分:0)

谢谢@mjim,但这段代码不起作用。我修改了代码并且有效!这是我的解决方案:

schema.post('save', function(doc){
    var prod = ProdProv.findById(this.prodprov).exec().then((pp) => {
        pp.quantitySold += this.quantity;
        pp.save();
    });
});