You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose中isModified何时返回false?为何我的代码始终返回true?

Why isModified() Always Returns True in Your pre('save') Hook

Let's break down what's happening here and show you when it will return false.

First: Why your current code always returns true

Your code is creating a new document from scratch:

let user = new User; 
user.email = req.body.email; 
user.displayName = req.body.displayName; 
user.avatar = req.body.avatar; 
user.password = req.body.password; 
user.save(/* ... */);

For brand-new Mongoose documents, isModified() will always return true because you're initializing fields that were previously unset (the empty document has no values for these fields). Setting any field on a new document counts as a "modification" relative to its initial state.

When isModified() returns false

This method returns false when you're working with an existing document fetched from the database and you don't change any of its fields before calling save(). Here's a concrete example:

// Fetch an existing user from the database
User.findById(someExistingUserId, (err, user) => {
  if (err) {
    return res.status(500).send({ Message: `Error fetching user: ${err}` });
  }

  // Don't modify any fields here
  user.save((err, userStored) => {
    // In your pre('save') hook, this.isModified() will return false now!
    if (err) return res.status(500).send({ Message: `Error saving: ${err}` });
    res.status(200).send({ user: userStored });
  });
});

Another scenario: if you modify a field but then revert it back to its original value before saving:

User.findById(someExistingUserId, (err, user) => {
  const originalName = user.displayName;
  
  // Modify the field (isModified() becomes true)
  user.displayName = "Temporary Name";
  console.log(user.isModified()); // Logs true

  // Revert to original value
  user.displayName = originalName;
  console.log(user.isModified()); // Logs false

  // Save now - pre('save') hook will see isModified() = false
  user.save();
});

Quick recap of how isModified() works

Mongoose tracks changes to a document from two states:

  1. For new documents: the initial empty state (all fields unset)
  2. For fetched documents: the state as it was when loaded from the database

Any change from that baseline triggers isModified() to return true; no changes (or reverting changes) make it return false.

内容的提问来源于stack exchange,提问作者Jamo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:41:29