Hi, I am struggling to understand why Mongoose is allowing me to create multiple documents with the same username, despite having set the “unique: true” on my username field. Here is my model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: { type: String, unique: true},
allTimeStats: [{
amountOfQuestions: Number,
amountOfCorrectAnswers: Number,
category: String
}],
ongoingGames: [{
opponent: String,
correctAnswers: Number,
opponentCorrectAnswers: Number,
dateOfOpponentsLastTurn: String,
img: String,
language: String
}],
searchingForGame: Boolean
});
const User = mongoose.model('User', userSchema);
module.exports = User;
And here is the call to the database:
const express = require('express');
const router = express.Router();
const User = require('../models/user');
// Add user
router.post('/', async (req, res) => {
const user = new User({
username: req.body.username,
allTimeStats: req.body.allTimeStats,
ongoingGames: req.body.ongoingGames,
searchingForGame: req.body.searchingForGame
});
try {
const savedUser = await user.save();
res.json(savedUser);
} catch(err){
res.json({message: err})
}
});
And here is a screenshot of multiple users having the same name
I just dropped the collection and tried again, and when I go to MongoDB Atlas and the collection and into Indexes, I don’t see an index for unique:true for username. Any help is appreciated.