猫鼬更新模型时未设置属性

时间:2020-08-07 09:48:34

标签: javascript node.js

如果创建了模型,则在此BaseSchame中有一个Schma,它必须为两个属性设置Value:

schema.pre("save", function (next) {
  if (!schema.isNew) {
    this.createDate = new Date();
    this.createBy = "kianoush";
}
  next();
});

如果必须为两个属性设置更新值:

  schema.pre("updateOne", function (next) {
    this.updateDate = new Date();
    this.updateBy = "kianoush";
    next();
  });

但是当我更新模型时,它不会保存updateDateupdateBy ..

 UpdateRole(role) {
    return new Promise((resolve, reject) => {
      Role.updateOne({ _id: role._id }, { $set: { ...role } }, (err, res) => {
        if (err) reject(err);
        else resolve(res);
      });
    });
  }

这是Controller:

await RoleReposiotry.UpdateRole(req.body)
      .then(() => {
        this.Ok(res);
      })
      .catch((err) => {
        this.BadRerquest(res, err);
      });

出什么问题了?我该如何解决这个问题?

更新:

  module.exports = function BaseSchema(schema, options) {
  schema.add({
    isDelete: { type: Boolean, default: false },
    owner: { type: String },
    updateDate: { type: String },
    updateBy: { type: String },
    deleteDate: { type: String },
    deleteby: { type: String },
    createDate: { type: String },
    createBy: { type: String },
  });

  schema.pre("save", function (next) {
    if (!schema.isNew) {
      this.createDate = new Date();
      this.createBy = "kianoush";
    }
    next();
  });

  schema.pre("updateOne", function (next) {
    this.updateDate = new Date();
    this.updateBy = "kianoush";
    next();
  });
};

这是角色表:

    const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const BaseSchema = require("./BaseSchema");

const RoleSchema = Schema({
  name: { type: String, require: true },
});


RoleSchema.plugin(BaseSchema);

module.exports = mongoose.model("Role", RoleSchema);

1 个答案:

答案 0 :(得分:1)

这部分文档提到“ updateOne”中间件无权访问文档,而是查询模型:https://mongoosejs.com/docs/middleware.html#notes

从上面的链接复制的用例示例:

schema.pre('updateOne', function() {
  this.set({ updatedAt: new Date() });
});