【发布时间】:2023-03-09 13:36:01
【问题描述】:
谁能解释如何在 mongoose (5.9.5) 中使用 updateOne 预挂钩?
我需要创建一个规范化的“影子字段”(不确定正确的术语)以帮助进行某些搜索。虽然我可以在保存过程中更新阴影场,但在更新过程中遇到了问题。
保存预挂钩:
personSchema.pre('save', function (next) {
if (this.isModified('name')) {
const name = this.name;
if (name && name.trim().length > 0) {
const shadowName = name.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
this.shadowName = shadowName.toLowerCase();
} else {;
this.shadowName = name;
}
}
// do stuff
next();
});
对updateOne 执行等效操作似乎不起作用(shadowName 保持初始保存时给出的值):
personSchema.pre('updateOne', function (next) {
const name = this.name;
if (name && name.trim().length > 0) {
const shadowName = name.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
this.update({}, { shadowName: shadowName.toLowerCase() });
} else {
this.shadowName = name;
}
// do stuff
next();
});
架构:
const personSchema = new mongoose.Schema({
resourceId: {
type: String,
required: true,
unique: true,
index: true,
uppercase: true
},
name:{
type: String,
required:true,
index: true
},
// can be used for searches, but don't update directly
shadowName: {
type: String,
index: true
},
});
顺便说一句,我可以确认调用了钩子,但该字段没有更新。
【问题讨论】:
标签: javascript node.js mongodb mongoose