Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I won’t do a batch insert job in MongoDB and I found two ways in mongoose:

One way is to 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 efficient?

2 Answers

0 votes
by (106k points)

The differences in Mongoose, there is Model.create and Collection.insert the latter isn't strictly part of Mongoose, but of the underlying MongoDB driver.

0 votes
by (108k points)

In Mongoose, there is Model.create and Collection.insert. According to the Mongoose developer, they are essentially the same when called with an array of documents, although looking at the code makes me think that there are subtle differences:

using Model.create will call any validators/hooks held 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.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
2 answers
0 votes
1 answer

Browse Categories

...