javascript - 在猫鼬中更新模型时未设置属性
问题描述
如果创建模型,我有一个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();
});
};
这是角色架构:
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”中间件无权访问文档,而是访问查询模型:https ://mongoosejs.com/docs/middleware.html#notes
从上面的链接复制的用例示例:
schema.pre('updateOne', function() {
this.set({ updatedAt: new Date() });
});
推荐阅读
- java - 如何获取 facebook 个人资料图片 url
- javascript - 用纯 Javascript 调用 Kotlin 传递的 Javascript 函数
- android - Crashlytics 发现无效的 API 密钥:null
- javascript - JavaScript 无法访问天气 API
- c++ - 如何使用 gdb 启动守护进程
- r - 如何在 R 中将 Pin Pad 创建为矩阵?
- android - Android:点击电话号码时如何显示我的应用程序(打开方式)
- vb.net - “Marshal.GetActiveObject”在获取对 CorelDRAW 的引用时给出 COMException
- php - Yii2 - 在运行时设置邮件传输参数
- javascript - Javascript 全局数组在所有页面上为空