Mongoose:Model.create 和 Collection.insert 有什么区别 [英] Mongoose: what's the differences between Model.create and Collection.insert

查看:29
本文介绍了Mongoose:Model.create 和 Collection.insert 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 MongoDB 中做一个批量插入工作,我在 mongoose 中找到了两种方法:

I want do a batch insert job in MongoDB and I found two ways in mongoose:

一种方法是使用insert:

dataArr = [
   {
       id: "",
       name: ""
   }
   {
       id: "",
       name: ""
   }
]

<代码>Collection.insert(dataArr)

另一种方式是Model.create:

Model.create(dataArr)

两者都可以完成批量插入作业,但它们之间有什么区别?

both could complete the batch insert job, but what's the difference between them?

哪个效率更高?

推荐答案

在 Mongoose 中,有 Model.createCollection.insert (后者严格来说不是 Mongoose 的一部分,而是底层 MongoDB 驱动程序的一部分).

In Mongoose, there is Model.create and Collection.insert (the latter isn't strictly part of Mongoose, but of the underlying MongoDB driver).

根据 Mongoose 开发人员的说法,当使用一组文档,虽然查看代码让我认为存在细微的差异(警告:我没有很好地查看代码,所以我可能会误认为以下内容):

According to the Mongoose developer, they are basically the same when called with an array of documents, although looking at the code makes me think that there are subtle differences (warning: I haven't looked at the code that well so I might be mistaken about the following):

  • 使用 Model.create 将调用在您的架构上声明的任何验证器/钩子;
  • Model.create 为数组中的每个文档做一个 .save,导致 N 个数据库调用(其中 N 是数组中的文档数);Collection.insert 执行一次大型数据库调用;
  • using Model.create will call any validators/hooks declared on your schema;
  • Model.create does a .save for each document in the array, resulting in N database calls (where N is the number of documents in the array); Collection.insert performs one large database call;

这篇关于Mongoose:Model.create 和 Collection.insert 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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