Mongoose (mongo), copy a document

mongodb, mongoose, node.js

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
});

Problem

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); }) }); ```

Original source