mongoose(mongo),复制文件

试图复制文件。 首先我find它。 然后删除_id。 然后插入它。 但是compute._id仍然存在。 所以我得到一个重复错误抛出。 我究竟做错了什么?

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

从findOne返回的对象不是一个普通对象,而是Mongoose文档。 您应该使用{lean:true}选项或.toObject()方法将其转换为普通的JavaScript对象。

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