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!
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.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
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.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With