gpt4 book ai didi

node.js - Mongoose(mongo),复制文档

转载 作者:行者123 更新时间:2023-12-02 09:50:42 25 4
gpt4 key购买 nike

正在尝试复制文档。首先我找到它。然后删除_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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com