mongoose save() 操作正在生成重复的 _id
mongoose save() operation is generating repeated _id
我有以下猫鼬模式:
var mongoose = require('mongoose');
module.exports = mongoose.model('lf', {
_set : {type:Number},
a : {type:String},
b : {type:String},
c : {type:Number},
created_at : {type: Date, default: Date.now},
updated_at : {type: Date, default: Date.now}
},'flr');
在我的代码中,我查询了一些集合并生成了一个包含上述模式的拼接 json 对象。
尽管当我对猫鼬进行 save() 操作时,我不断得到:
Collection1.findOne({tfC: tfC}).lean().then(FP=> {
if ( FP!== null && FP!== undefined ){
new linkedFixed(FP).save(function(err, result){
console.log(err);
process.exit();
});
}
}).catch(error => {
console.error(error);
});
我遇到错误:
{ MongoError: E11000 duplicate key error collection: Da.flr index: _id_ dup key: { : ObjectId('5a0c8b3f10dfe503505fcaec') } at Function.MongoError.create
我没有在我的架构中定义这个 _id 那么为什么猫鼬会在这个索引上生成重复的条目?
我能够理解查找到的 json 对象已经包含一个 _id。然后我删除它并收到错误:
MongooseError: document must have an _id before saving
如何在不传递 _id 的情况下将 json 对象保存到集合中? _id 不应该由 mongoose 随机分配且唯一吗?
问题出在lean()。当使用 lean _id 从 mongoose 查询返回时。
如果删除 lean() _id 不是文档内容的一部分,因此不会被覆盖。
在您的 findOne 方法中使用 $project 以避免从查询返回 _id(对象 ID),如下所示:
Collection1.findOne({tfC: tfC},{_id:0})
正如@JoaoFilipeClementeMartins 所说,问题在于 lean 你也在获取 _id,并且你正在将 _id 传递给新对象并尝试保存它。另一种可能的解决方案是在将 _id 设置到新对象之前将其删除。
delete FP._id;
new linkedFixed(FP).save(function(err, result){
我有以下猫鼬模式:
var mongoose = require('mongoose');
module.exports = mongoose.model('lf', {
_set : {type:Number},
a : {type:String},
b : {type:String},
c : {type:Number},
created_at : {type: Date, default: Date.now},
updated_at : {type: Date, default: Date.now}
},'flr');
在我的代码中,我查询了一些集合并生成了一个包含上述模式的拼接 json 对象。
尽管当我对猫鼬进行 save() 操作时,我不断得到:
Collection1.findOne({tfC: tfC}).lean().then(FP=> {
if ( FP!== null && FP!== undefined ){
new linkedFixed(FP).save(function(err, result){
console.log(err);
process.exit();
});
}
}).catch(error => {
console.error(error);
});
我遇到错误:
{ MongoError: E11000 duplicate key error collection: Da.flr index: _id_ dup key: { : ObjectId('5a0c8b3f10dfe503505fcaec') } at Function.MongoError.create
我没有在我的架构中定义这个 _id 那么为什么猫鼬会在这个索引上生成重复的条目?
我能够理解查找到的 json 对象已经包含一个 _id。然后我删除它并收到错误:
MongooseError: document must have an _id before saving
如何在不传递 _id 的情况下将 json 对象保存到集合中? _id 不应该由 mongoose 随机分配且唯一吗?
问题出在lean()。当使用 lean _id 从 mongoose 查询返回时。
如果删除 lean() _id 不是文档内容的一部分,因此不会被覆盖。
在您的 findOne 方法中使用 $project 以避免从查询返回 _id(对象 ID),如下所示:
Collection1.findOne({tfC: tfC},{_id:0})
正如@JoaoFilipeClementeMartins 所说,问题在于 lean 你也在获取 _id,并且你正在将 _id 传递给新对象并尝试保存它。另一种可能的解决方案是在将 _id 设置到新对象之前将其删除。
delete FP._id;
new linkedFixed(FP).save(function(err, result){