Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save multiple documents concurrently in Mongoose/Node.js?

At the moment I use save to add a single document. Suppose I have an array of documents that I wish to store as single objects. Is there a way of adding them all with a single function call and then getting a single callback when it is done? I could add all the documents individually but managing the callbacks to work out when everything is done would be problematic.

like image 903
Hoa Avatar asked Apr 22 '12 08:04

Hoa


People also ask

What does save () do in Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

What is difference between create and save in Mongoose?

create() is a shortcut for saving one or more documents to the database. MyModel. create(docs) does new MyModel(doc). save() for every doc in docs.

Does Mongoose automatically create collection?

exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.


1 Answers

Mongoose does now support passing multiple document structures to Model.create. To quote their API example, it supports being passed either an array or a varargs list of objects with a callback at the end:

Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {     if (err) // ... }); 

Or

var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; Candy.create(array, function (err, jellybean, snickers) {     if (err) // ... }); 

Edit: As many have noted, this does not perform a true bulk insert - it simply hides the complexity of calling save multiple times yourself. There are answers and comments below explaining how to use the actual Mongo driver to achieve a bulk insert in the interest of performance.

like image 165
Pascal Zajac Avatar answered Sep 20 '22 19:09

Pascal Zajac