尝试复制文档。首先,我找到它。然后删除_id。然后插入它。但是calculate._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);
})
});
答案 0 :(得分:6)
从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
});