Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

One way is use insert:

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

Collection.insert(dataArr)

and another way is Model.create:

Model.create(dataArr)

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

Which one is more efficiency?

like image 320
hh54188 Avatar asked Oct 31 '13 08:10

hh54188


People also ask

What is the difference between insert and create in MongoDB?

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.

Does Mongoose model create collection?

Mongoose by default does not create any collection for the model in the database until any documents are created.

What is create in Mongoose?

Mongoose models have a create() function that is often used to create new documents. const User = mongoose.model('User', mongoose.Schema({ email: String })); const doc = await User.create({ email: '[email protected]' }); doc instanceof User; // true doc.email; // '[email protected]'

What is the difference between schema and model in Mongoose?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.


2 Answers

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

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):

  • 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;
like image 78
robertklep Avatar answered Sep 25 '22 23:09

robertklep


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.

handle with care

like image 28
chuni Avatar answered Sep 23 '22 23:09

chuni