I have a BaseSchame
in this Schma
if Model is created it must set Value for two properties:
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
..
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:
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
Example of your use case copied from the link above:
schema.pre('updateOne', function() {
this.set({ updatedAt: new Date() });
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.