【发布时间】: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