Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB + Mongoose: Unique: true not working properly [duplicate]

I have a user.js model in my node app, and I'd like the username and a few other fields to be unique. In my model file I have properly declared the unique type seen below:

// User Schema
const UserSchema = new Schema({

    // PERSONAL USER INFO
    username: {
        type: String,
        required: true,
        index: true,
        unique: true,
    },
    email: {
        type: String,
        required: true,
        index: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
    },
    ....
});

However, after restarting both my server and mongo session, I can still create users with the same Username and the same Email. I can do this from both the mongo shell and the front-end user registration page.

Is there a second part to this that I'm missing? I'm not for sure how to properly enforce the unique type at this point. Thanks!

like image 390
jblew Avatar asked Feb 18 '18 21:02

jblew


People also ask

What does unique true do in Mongoose?

The unique option tells Mongoose that each document must have a unique value for a given path. For example, below is how you can tell Mongoose that a user's email must be unique. const mongoose = require('mongoose'); const userSchema = new mongoose.

How does MongoDB ensure unique values?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

What is __ V 0 in Mongoose?

This is __v field that is only generated when a document(s) is inserted through mongoose. The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.


1 Answers

Try deleting the database and running your program again, this is maybe because you add the constraint after the database creation and mongoose no recreate the index.

if you cannot delete you database try this in the mongo console

db.users.createIndex({username:1}, {unique:true})

see mongo unique index for more information

like image 145
stalin Avatar answered Nov 16 '22 11:11

stalin