问题
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