не устанавливать свойство при обновлении модели в мангусте - PullRequest
0 голосов
/ 07 августа 2020

У меня есть 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();
  });

но когда я обновляю модель, он не сохраняет updateDate и updateBy ..

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

и это Роль 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);

1 Ответ

1 голос
/ 07 августа 2020

В этой части документации упоминается, что промежуточное ПО updateOne не имеет доступа к документу, а вместо этого имеет модель запроса: https://mongoosejs.com/docs/middleware.html#notes

Пример вашего варианта использования, скопированного из ссылка выше:

schema.pre('updateOne', function() {
  this.set({ updatedAt: new Date() });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...