node.js Mongoose:Model.create 和 Collection.insert 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19701154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:08:50  来源:igfitidea点击:

Mongoose: what's the differences between Model.create and Collection.insert

node.jsmongodbinsertmongoose

提问by hh54188

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

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

One way is use insert:

一种方法是使用insert

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

Collection.insert(dataArr)

Collection.insert(dataArr)

and another way is Model.create:

另一种方法是Model.create

Model.create(dataArr)

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

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

Which one is more efficiency?

哪个效率更高?

回答by robertklep

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

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

According to the Mongoose developer, they are basically the samewhen 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 thatwell so I might be mistaken about the following):

根据 Mongoose 开发人员的说法,当使用文档数组调用它们时,它们基本上是相同的,尽管查看代码让我认为存在细微差别(警告:我没有很好地查看代码所以我可能会误会关于以下内容):

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

回答by chuni

according to what i've read, Collection.insert is a function of mongoDB driver it's much faster when inserting big amounts of data like millions or such at the cost that it bypasses mongoose validations.

根据我读过的内容,Collection.insert 是 mongoDB 驱动程序的一个函数,它在插入大量数据(如数百万或这样的数据)时要快得多,代价是它绕过了猫鼬验证。

handle with care

小心轻放

回答by Himansh

They loosely mean the same thing. You can use either of them.

它们的意思大致相同。您可以使用其中任何一个。