简体   繁体   English

更新 mongoose 中的 model 时未设置属性

[英]not set property when update the model in mongoose

I have a BaseSchame in this Schma if Model is created it must set Value for two properties:如果创建了 Model,我在这个Schma中有一个BaseSchame ,它必须为两个属性设置值:

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

if update must be set value for two property:如果必须为两个属性设置更新值:

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

but when I update the model it not save the updateDate and updateBy ..但是当我更新 model 时,它不会保存updateDateupdateBy ..

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

and this is Controller:这是Controller:

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

What's the problem?有什么问题? how can I solve this problem?我怎么解决这个问题?

Update:更新:

  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();
  });
};

and this is the Role Schame:这是角色架构:

    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);

This part of the docs mentions that "updateOne" middleware don't have access to document but the query model instead: https://mongoosejs.com/docs/middleware.html#notes这部分文档提到“updateOne”中间件无权访问文档,而是查询 model: https://mongoosejs.com/docs/middleware.html#notes

Example of your use case copied from the link above:从上面的链接复制的用例示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM