dan brown
dan brown

Reputation: 323

mongoDB mongoose unique index vs unique

I have a schema like this :

var UserSchema = new Schema({
    username : {
        type: String,
        required: true,
        unique : true,
        index: { unique: true },
        trim: true
    },
    password : {
        type: String,
        required: true
    }
})

on saving to db this gives me doc like this :

{
    "_id": {
        "$oid": "5b43827de210a92130b99ccf"
    },
    "username": "username1",
    "password": "password1",
    "__v": 0
}

The id changes for every doc.In this case even if i remove index: { unique: true } So is this necessary?or is just unique : true on username enough?

Upvotes: 1

Views: 728

Answers (1)

AAshish jha
AAshish jha

Reputation: 952

you can write two ways both are equivalent so you don't need to write both

name: { type: String, unique: true }

or

name: { type: String, index: { unique: true } }

Upvotes: 3

Related Questions