MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come salvare più raccolte mongodb usando Promise?

Usa Promise.all dentro save funzione, quindi puoi usarlo come ti aspetti

function save(){
    var promises = [
        new Promise(function(resolve, reject) {
            Collection1.collection.insert(collections1, function(err, done){
                 if(err)
                     reject(err);
                 else
                     resolve(done);
            });
        }),
        new Promise(function(resolve, reject) {
            Collection2.collection.insert(collections2, function(err, done){
                 if(err)
                     reject(err);
                 else
                     resolve(done);
            });
        }),
        new Promise(function(resolve, reject) {
            Collection3.collection.insert(collections3, function(err, done){
                 if(err)
                     reject(err);
                 else
                     resolve(done);
            });
        })
    ];
    return Promise.all(promises);
}

save().then(function(){
   console.log('success');
}).catch(function(){
   console.log('error');
})