【问题标题】:MongoError: E11000 duplicate key error, Although I did not have unique validation to any of my model propertiesMongoError:E11000 重复键错误,虽然我没有对我的任何模型属性进行唯一验证
【发布时间】:2023-03-11 16:53:01
【问题描述】:

我有一个像下面这样的学生模型,每个学生都可以订阅相同的测试

const mongoose = require('mongoose');

const StudentSubscriptionSchema = new mongoose.Schema({
    date: Date,
    expireDate: Date,
    status: String,
    subscriptionId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'subscriptions'
    }
});

const StudentSchema = new mongoose.Schema({
    account: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'users'
    },
    testSubscriptions: [{
        test: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'tests'
        },
        subscription: StudentSubscriptionSchema
    }],
    noteSubscriptions: [{
        note: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'notes'
        },
        subscription: StudentSubscriptionSchema
    }],
    testHistory: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'testhistory'
    }]
}, { timestamps: true });

module.exports = mongoose.model('students', StudentSchema);

每当我尝试将相同的测试 _id 添加到多个学生的测试订阅时,它只会将一条记录传递给一个学生,对于下一个学生,它会引发重复键错误

check error MongoError: E11000 duplicate key error collection: xyzcollection.students index: testSubscriptions.test_1 dup key: { testSubscriptions.test: ObjectId('60bce0a7a28bec57b8c84f2c') }

下面是我尝试推送测试订阅的方法

const reqBody = {
        test: req.body.testId,
        subscription: {
            date: req.body.subscriptionDate,
            subscriptionId: req.body.subscriptionId,
            expireDate: req.body.getExpiryDate
        }
    };

student = await STUDENT.findByIdAndUpdate(req.params.id,
            {
                $push: { testSubscriptions: reqBody }
            }, {
            new: true,
            runValidators: true
        });

【问题讨论】:

  • 当你运行 mongo shell 时,db.students.getIndexes() 告诉你什么?
  • 我发现了这个问题,@AlexBlex 是的,有一个索引问题通过将 autoIndex: false 添加到我的学生架构来解决。

标签: node.js mongodb mongoose mongodb-query mongoose-schema


【解决方案1】:

MongoDB 文档“_id”字段是保留的,默认情况下每个集合每个文档都是唯一的,即使您没有在代码中明确定义为唯一(创建集合时,_id 字段上的唯一索引由mongod 进程) ...

【讨论】:

    猜你喜欢
    • 2022-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多