试图复制文档。首先我找到了。然后删除_id。然后将其插入。但是calculation._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
});
关于node.js - Mongoose (mongo),复制文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23583483/