Why is Mongoose letting me create several documents with same username?

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 asd

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.

Hello atk3,

Welcome to the MongoDB forums.

Has the unique index been created?

Can you run the db.collection.getIndexes() and send a screenshot of the results? Overall Mongoose isn’t really much of a solution for index management.

Due to this you may want to consider using the MongoDB Shell to handle these things, but that said indexes only have to be built if they are fresh, or you ran db.dropDatabase().

Mongoose v8.2.3: FAQ has an explanation on the unique section:

Q . I declared a schema property as unique but I can still save duplicates. What gives?

A . Mongoose doesn’t handle unique on its own: { name: { type: String, unique: true } } is just a shorthand for creating a MongoDB unique index on name . For example, if MongoDB doesn’t already have a unique index on name , the below code will not error despite the fact that unique is true.

Regards,

Brock_GL

1 Like

Hi Brock,

Thank you for taking time out of your day to help me. The problem was that the index hadn’t been created, which is what I suspected, as it wasn’t showing up in MongoDB Atlas. The problem here was sleep deprivation, and not MongoDB or Mongoose.

Hello atk3,

No worries at all! Should you need any further assistance, just let us know!

Regards,

Brock_GL

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.