isModified() in Mongoose - v5

Viewed 319

I am using the isModified() on the documents to perform certain logic. But the method seems to return false even after the specified field has changed.

Code snippet:

exports.updateUser = async (req, res, next) => {
    const userId = req.params.id
    
    const tmpUser = await userModel.findById(userId)
    console.log(`User email before update - ${tmpUser.email}`)

    const user = await userModel.findByIdAndUpdate(userId, {email: req.body.email}, { new: true })
    
    console.log(`User email after update - ${user.email}`)
    console.log(`Is Modified - ${user.isModified('email')}`)
   
    res.status(200).json({
        user
    })
}

Console:

User email before update - Test1@gmail.com
User email after update - Test12@gmail.com
Is Modified - false

The email field of the document is changed in database but the isModified() returns false.

Also suggest if I can use a hook or middleware for this update action. I have tried the pre hook of 'updateOne' but it is not working.

1 Answers

findByIdAndUpdate() does not trigger hooks thus isModified returns false (source about triggers: https://mongoosejs.com/docs/middleware.html#notes).

However, you can use a slightly different approach (updateOne) which would work (and provides identical functionality to yours):

const user = await userModel.updateOne({ _id: Types.ObjectId(userId ) }, { email: req.body.email });

And to check if email was updated, use: result.nModified. This will return either 1 or 0 (0 for being not modified).

Related