Do not Create records if one or more document exist

Viewed 17

I'm using .create() to add multiple records to the collection from an array .

if one of the records already exist i managed to show an error :

  await Field.create(fieldArr, function (error,items) {

    if(error && error.message.indexOf('duplicate key error') !== -1){
      return res.status(400).json({message:'EXIST'})

    }
// no error contiune 
})

this is working fine but If the error occurred the other fields that don't exist will get added.

is there any way to stop creating the records if one or many of the items in the array exist?

1 Answers

mongoose create is a specific wrapper, by looking at the create function source code you can see this line:

if (firstError) {
   return cb(firstError, savedDocs);
}

You can deduce from this that any documents saved before the error is thrown are already in the DB.

Essentially this is how all inserts work, imagine the overhead to constantly check ahead of time for a condition that is not real for most usecases.

What you can do is check this yourself before you start:

// _id should be replaced with whatever key can throw this error
const found = await Field.findOne({_id: {$in: fieldArr.map(v => v._id)}})
if (found) {
    return res.status(400).json({message:'EXIST'})
}
await Field.create(fieldArr, function (error,items) {

    if(error && error.message.indexOf('duplicate key error') !== -1){
        return res.status(400).json({message:'EXIST'})

    }
// no error contiune 
})
Related