.save() 和使用 update() 之间的猫鼬区别 [英] Mongoose difference between .save() and using update()

查看:20
本文介绍了.save() 和使用 update() 之间的猫鼬区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在mongoose中修改现有条目中的字段,使用有什么区别

model = new Model([...])model.field = '新值';模型.save();

还有这个

Model.update({[...]}, {$set: {field: 'new value'});

我问这个问题的原因是因为有人对我昨天发布的问题提出了建议:NodeJS 和 Mongo - 多个用户同时发送请求时的意外行为.此人建议使用更新而不是保存,我还不确定为什么会有所不同.

谢谢!

解决方案

首先是两个概念.您的应用程序是客户端,Mongodb 是服务器.

主要区别在于,使用 .save() 时,您的客户端代码中已经有一个对象,或者必须在回写数据之前从服务器检索数据,并且您正在编写支持整件事.

另一方面,.update() 不需要将数据从服务器加载到客户端.所有交互都发生在服务器端,而无需检索到客户端.因此,当您向现有文档添加内容时,.update() 可以通过这种方式非常高效.

此外,还有 .update()multi 参数,允许对多个符合查询条件的文档执行操作.>

使用 .update() 作为调用时,您会丢失一些便利方法中的一些东西,但某些操作的好处是您必须承担的权衡".有关这方面的更多信息以及可用选项,请参阅文档.>

简而言之 .save() 是客户端接口,.update() 是服务器端.

To modify a field in an existing entry in mongoose, what is the difference between using

model = new Model([...])
model.field = 'new value';
model.save();

and this

Model.update({[...]}, {$set: {field: 'new value'});

The reason I'm asking this question is because of someone's suggestion to an issue I posted yesterday: NodeJS and Mongo - Unexpected behaviors when multiple users send requests simultaneously. The person suggested to use update instead of save, and I'm not yet completely sure why it would make a difference.

Thanks!

解决方案

Two concepts first. Your application is the Client, Mongodb is the Server.

The main difference is that with .save() you already have an object in your client side code or had to retrieve the data from the server before you are writing it back, and you are writing back the whole thing.

On the other hand .update() does not require the data to be loaded to the client from the server. All of the interaction happens server side without retrieving to the client.So .update() can be very efficient in this way when you are adding content to existing documents.

In addition, there is the multi parameter to .update() that allows the actions to be performed on more than one document that matches the query condition.

There are some things in convenience methods that you lose when using .update() as a call, but the benefits for certain operations is the "trade-off" you have to bear. For more information on this, and the options available, see the documentation.

In short .save() is a client side interface, .update() is server side.

这篇关于.save() 和使用 update() 之间的猫鼬区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆