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

后端 未结 5 1679
野的像风
野的像风 2020-12-29 07:34

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, ca         


        
相关标签:
5条回答
  • 2020-12-29 07:41

    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
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-29 07:43

    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

    0 讨论(0)
  • 2020-12-29 07:52

    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

    0 讨论(0)
  • 2020-12-29 07:57

    This works with mongoose as well

    Laptop.insertMany(laptopData, function (err, laptop) {
      if (err) {
        console.log(err);
      };
      console.log(laptop);
    });
    
    0 讨论(0)
  • 2020-12-29 08:01

    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 讨论(0)
提交回复
热议问题