2014-05-10 137 views
1

試圖複製文檔。首先我找到它。然後刪除_id。然後插入它。但是calculate._id仍然存在。所以我得到了重複錯誤。我究竟做錯了什麼?貓鼬(mongo),複製文檔

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

回答

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