[英]not set property when update the model in mongoose
如果創建了 Model,我在這個Schma
中有一個BaseSchame
,它必須為兩個屬性設置值:
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();
});
但是當我更新 model 時,它不會保存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();
});
};
這是角色架構:
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);
這部分文檔提到“updateOne”中間件無權訪問文檔,而是查詢 model: https://mongoosejs.com/docs/middleware.html#notes
從上面的鏈接復制的用例示例:
schema.pre('updateOne', function() {
this.set({ updatedAt: new Date() });
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.