Search code examples
node.jsexpressmongooseuuid

Mongoose return duplicate key for new data


My issues are I am writing a script to store JSON on the database server by post request. There are such issues:

for the first time, every JSON is submitted successfully when the server is restarted. after that, no JSON data will be submitted and give mongoose duplicate id issue.

E11000 duplicate key error index: [database_name].[collection].$_id_ dup key: { : "2c73c49d-8ad2-49bf-b5a1-520aa595df17" }
  • a key generated by schemas like
new Schema({
  _id: { type: String, default: uuidv4() },
  ... // remainings
}
  • Post request call back is here
function (req, res) {
    models
     .create({'---': req.body.---, ..., ..., ..., ...})
     .then(result => res.json(result))
     .catch(err => {
       res.send(err.message);
     });
}

Solution

  • default parameter should be a function

    If you pass uuidv4() it will pass a generated value when creating the Schema, and will use that value for all documents.

    The schema should be defined like this.

    new Schema({
      _id: { type: String, default: uuidv4 },
      ... // remainings
    }