首页 > 解决方案 > 在猫鼬中更新模型时未设置属性

问题描述

如果创建模型,我有一个BaseSchame,它必须为两个属性设置值:Schma

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

标签: javascriptnode.js

解决方案


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

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

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

推荐阅读