【问题标题】:mongoose save() operation is generating repeated _idmongoose save() 操作正在生成重复的_id
【发布时间】:2018-05-13 16:02:24
【问题描述】:

我有以下猫鼬模式:

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 随机分配且唯一吗?

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    问题来自lean()。使用精益 _id 时,从 mongoose 查询返回。

    如果删除lea() _id 不是文档内容的一部分,因此不会被覆盖。

    【讨论】:

      【解决方案2】:

      在您的 findOne 方法中使用 $project 以避免 _id(对象 ID)从查询返回,如下所示: Collection1.findOne({tfC: tfC},{_id:0})

      更多详情请参考MongoDB Aggregation $project

      【讨论】:

        【解决方案3】:

        正如@JoaoFilipeClementeMartins 所说,问题在于精益你也得到了_id,并且你正在将_id 传递给新对象并试图保存它。另一种可能的解决方案是在将 _id 设置为新对象之前将其删除。

        delete FP._id;
        new linkedFixed(FP).save(function(err, result){
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-27
          • 2017-02-07
          • 2018-06-25
          • 2015-04-24
          • 2015-01-09
          • 1970-01-01
          • 2017-12-27
          相关资源
          最近更新 更多