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

后端 未结 13 1926
南笙
南笙 2020-12-07 10:20

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 si

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 10:58

    Here is an example of using MongoDB's Model.collection.insert() directly in Mongoose. Please note that if you don't have so many documents, say less than 100 documents, you don't need to use MongoDB's bulk operation (see this).

    MongoDB also supports bulk insert through passing an array of documents to the db.collection.insert() method.

    var mongoose = require('mongoose');
    
    var userSchema = mongoose.Schema({
      email : { type: String, index: { unique: true } },
      name  : String  
    }); 
    
    var User = mongoose.model('User', userSchema);
    
    
    function saveUsers(users) {
      User.collection.insert(users, function callback(error, insertedDocs) {
        // Here I use KrisKowal's Q (https://github.com/kriskowal/q) to return a promise, 
        // so that the caller of this function can act upon its success or failure
        if (!error)
          return Q.resolve(insertedDocs);
        else
          return Q.reject({ error: error });
      });
    }
    
    var users = [{email: 'foo@bar.com', name: 'foo'}, {email: 'baz@bar.com', name: 'baz'}];
    saveUsers(users).then(function() {
      // handle success case here
    })
    .fail(function(error) {
      // handle error case here
    });
    

提交回复
热议问题