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

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

问题描述

要修改mongoose中现有条目中的字段,使用

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();

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

我问这个问题的原因是因为有人建议我昨天发布的一个问题:< a href =https://stackoverflow.com/questions/22262114/nodejs-and-mongo-unexpected-behaviors-when-multiple-users-send-requests-simult> NodeJS和Mongo - 多个用户发送请求时出现意外行为同时的。这个人建议使用更新而不是保存,我还不完全确定为什么它会产生影响。

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.

谢谢!

推荐答案

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

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

主要区别在于 .save()你的客户端代码中已有一个对象,或者在你回写之前必须从服务器检索数据,而你正在回写整个事情。

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.

另一方面 .update() 要求将数据加载到来自服务器的客户端。所有交互都发生在服务器端而没有检索到客户端。当您向现有文档添加内容时,以这种方式 .update()非常有效。

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.

此外,还有参数到 .update()允许在多个与查询条件匹配的文档上执行操作。

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.

使用<$ c $时,便捷方法中有些东西会松动c> .update()作为一个电话,但某些操作的好处是你必须承担的权衡。有关此内容以及可用选项的详细信息,请参阅文档

There are some things in convenience methods that you loose 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.

简而言之 .save()是客户端界面, .update()是服务器端。

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

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

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