Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an array of objects to mongoose DB with only one call?

Is there any way to save an array of JSON object to a mongodb with only one call? something like:

schemeObject.save(array_of_json_object, callback);

I'm using mongoosejs

like image 787
jAckOdE Avatar asked Apr 03 '12 04:04

jAckOdE


People also ask

Can we store array of objects in MongoDB?

One of the benefits of MongoDB's rich schema model is the ability to store arrays as document field values. Storing arrays as field values allows you to model one-to-many or many-to-many relationships in a single document, instead of across separate collections as you might in a relational database.

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 save and create 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.


2 Answers

There is a way to batch insert with MongooseJS. I'm not sure if it's a new feature since this question was asked/answered, but I figured if someone were to come here from a search, they should know the way to do it.

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

Here are the docs: http://mongoosejs.com/docs/api.html#model_Model.create

like image 75
Dan Mandle Avatar answered Oct 04 '22 02:10

Dan Mandle


I do not think its possible with mongooosejs. You can however use BATCH insert of mongodb ,which is supported natively.

Helpful links:

http://www.mongodb.org/display/DOCS/Inserting#Inserting-Bulkinserts

https://groups.google.com/forum/#!msg/mongoose-orm/IkPmvcd0kds/bZuYCN_orckJ

like image 45
DhruvPathak Avatar answered Oct 04 '22 03:10

DhruvPathak