I'm having difficulty understanding what's the better way to update a document in Mongoose with Node.js. If you set the properties of a document like so:
const oldUser = UserModel.findOne({ name: user.userid });
oldUser.firstName = user.firstName || oldUser.firstName;
oldUser.lastName = user.lastName || oldUser.lastName;
then when you reach the document.save() method inside a pre-save hook your document is not set as modified. The isModified() is always false. However, when you use set()
you do get the document set to true for isModified()
for example:
const oldUser = await UserModel.findOne({ name: user.name });
oldUser.set('firstName', user.firstName || oldUser.firstName);
oldUser.set('lastName', user.lastName || oldUser.lastName);
Which is a better way to update a document and check for if it really was modified or not, and is there a better approach that's different than these two? Any tips, advice, or suggestions appreciated!