我觉得我遗漏了一些非常简单的东西,但是我无法获得要更新的contact.fullName
值。contact.middleName
会按预期进行更新。
钩子被触发,所做的更改会反映在conlog中,但不会反映在DB中。fullName
字段拒绝更新,但没有抛出错误。我感觉我在这里失去了理智
Mongoose模式/模型:
const Contact = new mongoose.Schema({
firstName: { type: String, required: true },
middleName: { type: String, required: false },
lastName: { type: String, required: true },
fullName: { type: String, required: false },
});
// When a Contact is created, we populate the `fullName` field using a pre-save
// hook, which is working as expected:
Contact.pre('save', function (next) {
const contact = this;
contact.fullName = `${contact.firstName || ''} ${contact.lastName || ''}`;
return next();
});
// on update, we want to update the fullName field as well. This is broken:
Contact.pre(\(updateOne|update)\, function (next) {
const contact = this;
const update = contact._update['$set'];
const newFullName = `${update['firstName'] || ''} ${update['lastName'] || ''}`;
console.log(newFullName);
contact.fullName = newFullName;
console.log(contact.fullName); // i can see the correctly updated value here!
if (update['middleName']) contact.middleName = update['middleName'];
console.log(contact.middleName); // i can also see this one!
return next();
});
调用updateOne
操作的函数(如果相关):
module.exports.updateContact = (req, res, next) => {
const { contact } = req.body;
Contact.updateOne({ _id: contactId }, { $set: { ...contact } }, (err, result) => {
if (err) return next(err);
return next(result);
});
};
发布于 2021-05-05 10:11:49
问题是因为您调用的是Query#updateOne()
,而不是Document#updateOne()
,所以它将触发pre('updateOne')
查询中间件,并且this
将引用查询,而不是文档。在这种情况下,您应该将代码修改为类似以下内容:
Contact.pre(\(updateOne|update)\, function (next) {
const update = contact._update['$set'];
const newFullName = `${update['firstName'] || ''} ${update['lastName'] || ''}`;
this.set({ fullName: newFullName })
return next();
});
更详细的here。
https://stackoverflow.com/questions/67390900
复制相似问题