要修改mongoose中现有条目中的字段,使用之间有什么区别
model = new Model([...]) model.field = 'new value'; model.save();
还有这个
Model.update({[...]}, {$set: {field: 'new value'});
我问这个问题的原因是因为有人建议我昨天发布的一个问题:NodeJS和Mongo - 当多个用户同时发送请求时出现意外行为.这个人建议使用更新而不是保存,我还不完全确定它为什么会有所作为.
谢谢!
首先是两个概念.您的应用程序是客户端,Mongodb是服务器.
主要的区别在于,.save()
在您的客户端代码中已经有了一个对象,或者在您将其写回之前必须从服务器检索数据,并且您正在回写整个事情.
另一方面.update()
,不要求将数据从服务器加载到客户端.所有的交互都发生在服务器端而没有检索到客户端.update()
.因此,当您向现有文档添加内容时,这种方式非常有效.
此外,还有一个multi
参数.update()
允许在多个与查询条件匹配的文档上执行操作.
在使用便捷方法时,有些东西在.update()
用作通话时会松动,但某些操作的好处是你必须承担的"权衡".有关此内容以及可用选项的详细信息,请参阅文档.
简而言之.save()
就是客户端接口,.update()
是服务器端.
一些差异:
如其他地方所述,update
比find
后续更有效,save
因为它避免加载整个文档.
Mongoose update
转换为MongoDB,update
但Mongoose save
转换为MongoDB insert
(用于新文档)或update
.
重要的是要注意,在save
,猫鼬内部的diff文件,只发送实际变化的领域.这对原子性有好处.
默认情况下,验证不会运行,update
但可以启用它.
中间件API(pre
和post
钩子)是不同的.
Mongoose上有一个名为Middleware的有用功能.有'pre'和'post'中间件.当您执行"保存"时,中间件会被执行,但在"更新"期间不会执行.例如,如果要在每次修改密码时在User模式中哈希密码,可以使用pre来执行以下操作.另一个有用的示例是为每个文档设置lastModified.该文档可以在http://mongoosejs.com/docs/middleware.html找到
UserSchema.pre('save', function(next) { var user = this; // only hash the password if it has been modified (or is new) if (!user.isModified('password')) { console.log('password not modified'); return next(); } console.log('password modified'); // generate a salt bcrypt.genSalt(10, function(err, salt) { if (err) { return next(err); } // hash the password along with our new salt bcrypt.hash(user.password, salt, function(err, hash) { if (err) { return next(err); } // override the cleartext password with the hashed one user.password = hash; next(); }); }); });