Mongoose MODEL update() vs save() Mongoose MODEL update() vs save() mongoose mongoose

Mongoose MODEL update() vs save()


First of all, you don't need to call foundUser.save() when you are using foundUser.update() method.

And, all the above methods are almost equally efficient as there are two calls being made to the database. So, it comes down to your personal preference.

And, one more method with just one call to the database can be executed in this manner:-

let foundUser = await userModel.findOneAndUpdate( { email: recievedEmail, password: hashedPassword }, { $set: { lastLogin: new Date() }, $push: { myEvents: authEvent } });

In this method, if a user with given email and password exists, that user will be updated and corresponding updated document will be returned in a foundUser variable. So you don't have to perform an additional check on password: If findOneAndUpdate() returns a document, it means password and email matched. You have just to check for null or undefined on the returned document for no match.