Question

Trying to copy a document. First I find it. Then removing the _id. Then inserting it. But the calculation._id is still there. So I get a duplication error thrown. What am I doing wrong?

mongoose.model('calculations').findOne({calcId:req.params.calcId}, function(){
      if(err) handleErr(err, res, 'Something went wrong when trying to find calculation by id');

      delete calculation._id;
      console.log(calculation); //The _.id is still there
      mongoose.model('calculations').create(calculation, function(err, stat){
        if(err) handleErr(err, res, 'Something went wrong when trying to copy a calculation');
        res.send(200);
      })
    });
Was it helpful?

Solution

Object returned from findOne is not a plain object but Mongoose document. You should use {lean:true} option or .toObject() method to convert it into plain JavaScript object.

mongoose.model('calculations').findOne({calcId:req.params.calcId}, function(err,calculation){
  if(err) handleErr(err, res, 'Something went wrong when trying to find calculation by id');

  var plainCalculation = calculation.toObject();


  delete plainCalculation._id;
  console.log(plainCalculation); //no _id here
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top