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