Mongoose MODEL update() vs save()

隐身守侯 提交于 2019-12-11 17:46:07

问题


There were a question about update() vs save(), but it was targeting some different stuff (I guess, purely related mongoose.Schema methods, but not to the actual document)

I have a following scenario, where user logs in to website:

  • I need to load document (find it by userModel.email)
  • Check if a userModel.password hash matches to what was recieved
  • Update userModel.lastLogin timestamp
  • Append authorization event to userModel.myEvents[] array

So I am wondering - what is a proper way to go?

1)

let foundUser = userModel.findOne({ email: recievedEmail });
if(foundUser.password != recievedPassword)
    return res.status(400).json({e: "invalid pass"});
foundUser.lastLogin = new Date();
foundUser.myEvents.push(authEvent)
foundUser.save();

2)

let foundUser = userModel.findOne({ email: recievedEmail });
if(foundUser.password != recievedPassword)
    return res.status(400).json({e: "invalid pass"});
foundUser.update({
    $push: { myEvents: authEvent },
    $set: { lastLogin: new Date() }
});
foundUser.save();

3)

let foundUser = userModel.findOne({ email: recievedEmail });
if(foundUser.password != recievedPassword)
    return res.status(400).json({e: "invalid pass"});
userModel.updateOne({_id: foundUser._id}, {$push: ...
// seems no save is required here?

4)

// I am doing it wrong, and you have faster/higher/stronger variant?

回答1:


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.



来源:https://stackoverflow.com/questions/55303400/mongoose-model-update-vs-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!