0

There's a method Model#create in a Mongoose to which I can send an array of objects.

var items = [{id: 1},{id: 2},{id: 3},{id: 4}];
Model.create(array, function (err, succededItems) {
   ...
});

Everything works fine except behavior when some of the objects which I try to create failed to be saved. In this scenario in err object I get, there're details about first object which has been failed, and in succededItems I get an array of the objects which have been saved.

I doubt is it possible to get in err or other way, an array which objects failed to save and reason, why did this happen?

Thank you in advance.

1 Answer 1

2

Unfortunately Mongoose returns only the first error, so your best option would be to use a combination of promises :

Promise
    .all( items.map( item => {
         return Model.create( item ) 
                     .catch( error => ( { error } ) )
    }) )
    .then( items => {

         items.forEach( item => {
             if ( item.error ) {
                console.log( "Item has failed with error", item.error );
             } else {
                console.log( "Item created successfully" );
             }
         } );

    } );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.