I am using Model.create(Array) in Mongoose.
I want to provide user a feedback about how many documents have been created and how many of them haven't (i.e. they didn't validate).
I created a callback like this
User.create(usersToImport, function(err, docs) {
console.log(err);
console.log(docs);
}
The problem is that if any document does not validate, I only receive a validation error on the single non-valid document, while I cannot retrieve any information about the inserted documents.
Is there any way to get this information?
I think, you need something like .settle()
method from when.js
module.
Here is an example of doing it using when.js
with mongoose 3.8.x
:
when = require('when');
promises = usersToImport.map(function(user) {
return User.create(user); // returns Promise
});
when.settle(promises).then(function(results) {
// results is an array, containing following elements:
// { state: 'fulfilled', value: <document> }
// { state: 'rejected', value: <error> }
});
It's possible to do it without Promises (e.g. using async
module), but the code will be much more complicated.
Model.create()
isn't going to return that information for you. The best option would be to roll your own version of Model.create()
, which is essentially a convenience method for calling Model.save()
multiple times, and collate the information yourself. A good way to get started is the code for Model.create()
.