问题描述
有一个有关update()
vs save()
的问题,但它的目标是一些不同的东西(我想是完全相关的mongoose.Schema
方法,但与实际文档无关)
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:
- 我需要加载文档(由
userModel.email
查找) - 检查
userModel.password
哈希是否与收到的内容匹配 - 更新
userModel.lastLogin
时间戳 - 将授权事件附加到
userModel.myEvents[]
阵列
- 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
所以我想知道-什么是正确的选择方式?
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?
推荐答案
首先,在使用foundUser.update()方法时,无需调用foundUser.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 } }
);
在这种方法中,如果存在具有给定电子邮件和密码的用户,则该用户将被更新,并且相应的更新文档将在foundUser
变量中返回.因此,您不必对密码进行其他检查:如果findOneAndUpdate()
返回文档,则意味着密码和电子邮件匹配.您只需要检查返回的文档中是否为null或undefined即可.
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.
这篇关于猫鼬模型update()vs save()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!