I want to save 8 objects to a MongoDB database using Mongoose. When the last document is saved, I want to report (i.e. send an event) that all documents have been saved.
The way I'm doing it now is quite messy (especially for increasingly larger amounts of documents I want to save).
This is how I have it now (just for 4 people for this example). Is there a cleaner way you can recommend?
person1.save(function(err, result){
if (err) console.log(err);
else{
person2.save(function(err, result){
if (err) console.log(err);
else{
person3.save(function(err, result){
if (err) console.log(err);
else{
person4.save(function(err, result){
if (err) console.log(err);
else{
done();
}
});
}
});
}
});
}
});
I want to save 8 objects to a MongoDB database using Mongoose. When the last document is saved, I want to report (i.e. send an event) that all documents have been saved.
The way I'm doing it now is quite messy (especially for increasingly larger amounts of documents I want to save).
This is how I have it now (just for 4 people for this example). Is there a cleaner way you can recommend?
person1.save(function(err, result){
if (err) console.log(err);
else{
person2.save(function(err, result){
if (err) console.log(err);
else{
person3.save(function(err, result){
if (err) console.log(err);
else{
person4.save(function(err, result){
if (err) console.log(err);
else{
done();
}
});
}
});
}
});
}
});
Share
Improve this question
asked Jul 10, 2015 at 20:05
CodyBugsteinCodyBugstein
23.3k67 gold badges224 silver badges381 bronze badges
0
5 Answers
Reset to default 12A useful library to coordinate asynchronous operations is async
. In your case, the code would look something like this:
var people = [ person1, person2, person3, person4, ... ];
async.eachSeries(people, function(person, asyncdone) {
person.save(asyncdone);
}, function(err) {
if (err) return console.log(err);
done(); // or `done(err)` if you want the pass the error up
});
Using promises and Array.map()
const userPromises = persons.map(user => {
return new Promise((resolve, reject) => {
person.save((error, result) => {
if (error) {
reject(error)
}
resolve(result);
})
})
});
Promise.all(userPromises).then((results) => {
//yay!
//results = [first, second, etc...]
}, (error) => {
//nay!
})
I would recommend to have an array and save with iteration. Will have same performance but code would be cleaner.
You can have
var Person = mongoose.model('Person');
var people = [];
people[0] = new Person({id: 'someid'});
people[0].set('name', 'Mario');
people[1] = new Person({id: 'someid'});
people[1].set('name', 'Mario');
people[2] = new Person({id: 'someid'});
people[2].set('name', 'Mario');
var errors = [];
for(person in people){
people[person].save(function(err, done){
if(err) errors.push(err);
if (person === people.length){ yourCallbackFunction(errors){
if (errors.length!=0) console.log(errors);
//yourcode here
};
}
});
}
The best way is to use async waterfall. Part of the code snippet might look as below. Please refer the above link. It breaks the async nature and converts into a one after another process (if I am not wrong).
waterfall([
function(callback){
callback(null, 'one', 'two');
},
function(arg1, arg2, callback){
callback(null, 'three');
},
function(arg1, callback){
// arg1 now equals 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
I would use Underscore Each to iterate over an array of People models. This would lead to your code being cleaner and help avoid the "boomerang effect" you are experiencing with your code.
From the documentation:
.each(list, iteratee, [context]) Alias: forEach
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining.
For example:
var people = [person1, person2];
var length = people.length;
var hasError = false;
var doSomething = function() {
console.log("I'm done");
}
var doSomethingElse = function() {
console.log('There was an error');
}
_.each(people, function(person, i) {
if (!hasError) {
person.save(function(err, result) {
if (err) {
console.log(err);
hasError = true;
}
);
if (i === length) {
doSomething();
}
} else {
// There was an error
doSomethingElse();
}
});