【问题标题】:Changes in Mongoose pre-save hook is not reflecting in dbMongoose 预保存挂钩的更改未反映在数据库中
【发布时间】:2017-07-30 19:52:36
【问题描述】:

我正在更新 mongoose 预保存挂钩中的必填字段 procedureid 的值。但是,这并没有反映在我的 MongoDB 中。

我在这里做错了什么?

const collection = 'hospital_doctor_details';
var hospitalDoctorSchema = new Schema({

    Treatment: [{        
        procedureid: { type: Number, required: true},        
    }],
    updated_at: { type: Date, required: true, default: Date.now }
});


hospitalDoctorSchema.pre('save', function (next) {

    var self = this;
    var treatmentcnt =parseInt( this.Treatment.length)-1
    self.Treatment[treatmentcnt].procedureid= 1234;

   next();

});

//create collection.
module.exports.hospitalModel = mongoose.model(collection, hospitalDoctorSchema);

【问题讨论】:

  • 在架构中定义了procedureid,那么为什么要在预保存中插入departmentId
  • 抱歉。从大型模型中复制一些重要的代码 sn-p 时出现拼写错误。问题现已更正。
  • 在创建 obj 时,你是通过 [{procedureid: "something"}] 还是什么都不传递?因为如果什么都没有,它应该抛出错误,因为Treatment 还不存在。如果你能说出你到底想达到什么目标,那将会很有帮助。可能有更好的解决方案。
  • procedure id 是一个唯一的自动生成编号。每当管理员插入一个新程序时,它都会创建一个新的唯一编号并分配给 procedureid。因为它是由服务器端代码在内部创建的,[{procedureid: "something "}] 不是从控制器传递的,而是我更喜欢在每次 api 调用期间自动生成
  • 治疗是一个数组。所以你的意思是说每当你创建(或稍后更新)时,它应该插入一个带有新procedureid的新对象?

标签: node.js mongoose


【解决方案1】:

preSave 中,您正在尝试访问一个数组,据我所知,您的 cmets 在创建时不存在该数组。因此,您需要将空数组分配给Treatment,然后推送一个包含procedureid 的对象。

hospitalDoctorSchema.pre('save', function (next) {
    this.Treatment = this.Treatment? this.Treatment : []; 
    this.Treatment.push({
        procedureid : 1234
    });
   next();
});

这将在后续保存时将更多对象推送到 Treatment 数组(findsave),这似乎是您想要的。

【讨论】:

  • 是的,你的理解是正确的。但是,somwhoe procedureid 并没有反映在使用上述代码 n-p 的 db 中
  • preSave 应该在模型还是控制器中?
  • 在模型中,正是您在问题中放置的位置。
猜你喜欢
  • 2015-08-29
  • 2016-09-18
  • 1970-01-01
  • 2016-06-07
  • 2020-04-23
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 2018-01-14
相关资源
最近更新 更多