发布
社区首页 >问答首页 >Mongoose预更新钩子工作,但更改不会反映在数据库中

Mongoose预更新钩子工作,但更改不会反映在数据库中
EN

Stack Overflow用户
提问于 2021-05-05 03:20:47
回答 1查看 188关注 0票数 0

我觉得我遗漏了一些非常简单的东西,但是我无法获得要更新的contact.fullName值。contact.middleName会按预期进行更新。

钩子被触发,所做的更改会反映在conlog中,但不会反映在DB中。fullName字段拒绝更新,但没有抛出错误。我感觉我在这里失去了理智

Mongoose模式/模型:

代码语言:javascript
代码运行次数:0
复制
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操作的函数(如果相关):

代码语言:javascript
代码运行次数:0
复制
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);
  });
};
EN

回答 1

Stack Overflow用户

发布于 2021-05-05 10:11:49

问题是因为您调用的是Query#updateOne(),而不是Document#updateOne(),所以它将触发pre('updateOne')查询中间件,并且this将引用查询,而不是文档。在这种情况下,您应该将代码修改为类似以下内容:

代码语言:javascript
代码运行次数:0
复制
Contact.pre(\(updateOne|update)\, function (next) {
  const update = contact._update['$set'];

  const newFullName = `${update['firstName'] || ''} ${update['lastName'] || ''}`;

  this.set({ fullName: newFullName })

  return next();
});

更详细的here

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67390900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档