Trying to save user Progress and I get this error with Mongodb. I included the User Save Post Route, Along with my monogdb user schema and lesson schema. I removed the unquie part and sitll get this error. I am trying to create is so that each User gets their own Progress Array, and in that array once they complete a lesson it saves theirs attempts and score in there. But I run into the duplicate error.
MongoServerError: E11000 duplicate key error collection: 6400ca2c7c9bbc2178e3deec_test.users index: progress.sublessonId_1 dup key: { progress.sublessonId: ObjectId(‘64b49d139fe2b8ed132e0bd8’) }
Code -
saveUserProgress.post('/api/saveProgress', verifySession(), async (req: Request, res: Response) => {
let { userId, lessonId, sublessonId, completed, score } = req.body;
if (!userId || !lessonId || !sublessonId || completed === undefined || score === undefined) {
return res.status(400).json({ error: 'Invalid request body.' });
}
try {
// Find the user by their user_id
const user = await User.findOne({ user_id: userId });
if (!user) {
return res.status(404).json({ error: 'User not found.' });
}
// Check if the lessonId and sublessonId already exist in the progress array
const existingProgressIndex = user.progress.findIndex((item: any) => {
return (
item.Lessons &&
item.sublessonId &&
item.Lessons.toString() === lessonId &&
item.sublessonId.toString() === sublessonId
);
});
if (existingProgressIndex !== -1) {
const existingProgress = user.progress[existingProgressIndex];
// If the completedDate is already set, don't update it
if (existingProgress.completedDate) {
completed = existingProgress.completed;
} else if (completed) {
existingProgress.completedDate = new Date();
}
existingProgress.completed = completed;
existingProgress.score = score;
existingProgress.highestScore = Math.max(existingProgress.highestScore, score);
existingProgress.attempts += 1;
} else {
// If the progress doesn't exist, add a new progress object to the array
user.progress.push({
Lessons: lessonId,
sublessonId: sublessonId,
completed: completed,
completedDate: completed ? new Date() : null,
attempts: 1,
score: score,
highestScore: score,
});
}
// Save the updated user object
await user.save();
res.json({ message: 'User progress saved successfully.' });
} catch (error) {
console.log(error);
res.status(500).json({ error: 'Error saving user progress.' });
}
return;
});
This is my Schema,
const userSchema = new mongoose.Schema({
//requires email and password - Add Username so it can be added to profile later
email: {
type: String,
required: [true, "Please provide an Email Address."],
unique: [true, "Email already Exists."]
},
user_id: {
//Supertokens user id
type: String,
required: true,
},
/* Non Required - Update in Profile*/
firstName: {
type: String,
},
lastName: {
type: String,
},
dateOfBirth: {
type: Number,
},
location: {
type: String,
},
date: {
type: Number,
},
/* Non Required - Update in Profile*/
/* Progress */
progress: {
type: Array,
of: {
Lessons: {
type: Types.ObjectId,
ref: "Lesson",
},
sublessonId: {
type: Types.ObjectId,
ref: "Lesson.lessons",
},
completed: {
type: Boolean,
default: false,
},
completedDate: {
type: Date,
},
attempts: {
type: Number,
default: 0,
},
score: {
type: Number,
},
highestScore: {
type: Number,
},
},
},
})