.save()和使用update()之间的Mongoose区别
要修改mongoose现有条目中的字段,使用什么区别
model = new Model([...]) model.field = 'new value'; model.save();
和这个
Model.update({[...]}, {$set: {field: 'new value'});
我问这个问题的原因是有人对我昨天发布的问题的build议: NodeJS和Mongo – 多个用户同时发送请求时的意外行为 。 该人build议使用更新,而不是保存,我还不完全确定为什么它会有所作为。
谢谢!
两个概念第一。 您的应用程序是客户端 ,Mongodb是服务器 。
主要区别在于.save()
在客户端代码中已经有了一个对象,或者在写回数据之前必须从服务器检索数据,而且您正在写回所有东西。
另一方面.update()
不需要从服务器将数据加载到客户端。 所有的交互都发生在服务器端而不需要检索到客户端。所以当你向现有文档添加内容时.update()
可以非常高效。
此外, .update()
的multi
参数允许在多个匹配查询条件的文档上执行操作。
在使用.update()
作为调用的时候,有一些方便的方法,但是对某些操作的好处是你必须承担的“权衡”。 有关这方面的更多信息和可用选项,请参阅文档 。
简而言之, .save()
是客户端接口, .update()
是服务器端。
有些区别:
- 正如其他地方所指出的,
update
比find
和save
更有效,因为它避免了加载整个文档。 - Mongoose
update
翻译成MongoDBupdate
但是Mongoosesave
被转换为MongoDBinsert
(用于新文档)或update
。 - 需要注意的是,在
save
, Mongoose会在内部区分文档 ,只发送实际更改的字段。 这对primefaces性是有利的。 - 默认情况下, validation不在
update
运行 ,但可以启用。 - 中间件API(
pre
钩子)是不同的。
Mongoose中间件有一个有用的function。 有“前”和“后”中间件。 中间件在执行“保存”时执行,而不在“更新”中执行。 例如,如果要在每次修改密码时在用户模式中散列密码,则可以使用pre按如下所示进行操作。 另一个有用的例子是为每个文档设置lastModified。 该文档可以在http://mongoosejs.com/docs/middleware.htmlfind
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(); }); }); });