20

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

4
  • Can you please update the correct answer?
    – Dan Mandle
    May 20, 2015 at 20:38
  • @IcyFlame Your linked post is technically a duplicate of this one.
    – Dan Mandle
    Sep 8, 2016 at 21:38
  • @DanMandle right! I didn't notice the dates. Thanks for pointing out.
    – IcyFlame
    Sep 10, 2016 at 6:15
  • You can also try this: stackoverflow.com/questions/16726330/…
    – IcyFlame
    Sep 10, 2016 at 6:15

6 Answers 6

32

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

2
  • 4
    That should work if we want to create new docs. How about update a array or docs that returned from a query?
    – jAckOdE
    Apr 10, 2014 at 6:41
  • For that, I think you'd have to do a find() then a forEach() on the result, update the values and do a save() for each of them. But I'm pretty new to Mongoose myself.
    – Dan Mandle
    Apr 11, 2014 at 14:23
10

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

1
  • 3
    the answer is found in the second link. Thanks
    – jAckOdE
    Apr 3, 2012 at 10:49
2

This works with mongoose as well

Laptop.insertMany(laptopData, function (err, laptop) {
  if (err) {
    console.log(err);
  };
  console.log(laptop);
});
0

How about something like this? I know it loops through the entire array.. dont ask me about the Big O for this.. probably not the best way to insert but works for just an initial data dump of some sort..

var arr = // array of objects;
    res = [];

arr.forEach(function (item) {
    item.save(function (err) {
        res.push(err);
        if (res.length === arr.length)
        {
            // Done
        }
    });
});
1
  • that woudnt be a batch insert if its one by one!
    – Pinser
    Apr 8, 2015 at 6:33
0

Another workaround that I've used. If you are using mongoose with promises, you can do this using Q.

You can start using Q as the default promise for mongoose using the below code:

const mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;

Then you can save an array of documents like below. Let's say we are storing an array of User models, which I've shown in users variable.

Q
  .all(users.map(curr => curr.save()))
  .then((results) => { //do something })
  .catch((err) => { //handle error })

.save() will return a q promise and using array map function, we'll create a promise array using the user models array.

0

I got the solution instead of using

new model_name({
your data
})

use this

model_name.create({your data}).then(res).catch(err) 

// simple promise things

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.