Christopher W
Christopher W

Reputation: 136

Mongoose vs MongoDB validation

I have a project I am working on and was following a guide for user creation. The goal was to create a user with a unique username and unique email and bcrypt password. No other user should be able to sign up using either the username or email, once one is used.

The process involved creating the user, using the below Schema via a Post request, using postman. The "unique" indicator was added after a user had already been created. After I updated the Schema to include the "unique" option, I found that users could still be created with the same email. While searching on here I found that was due to the initial documents being created with that email and that was resolved by removing that collection and starting fresh, not a big problem.

var UserSchema = new Schema({
username: { type: String, lowercase: true, required: true, unique: 
true},
password: { type: String, required: true },
email: { type: String, required: true, lowercase: true, unique: true}
});

However, while researching the Mongoose website I found some info on validation that has left me a bit confused. I was looking at the validation docs and then FAQ on the Mongoose site which from what I can tell states I should instead, in production, use MongoDB shell to create the indexes for my data, if I want them to be confirmed unique on creation, instead of using the "unique" option.

Is this correct? Or, why would I ever use "unique" in Mongoose when Mongoose is telling me that in the end I will actually need to use MongoDB Shell? With the Schema validation available in MongoDB is Mongoose still a preferred option to use when developing MEAN apps, today? I do see Mongoose frequently used but I don't have any huge opinions or need to make something as relational as possible, is Mongoose still worth learning over just using MongoDB itself? If I am so wrong it hurts that is fine and I can accept that but any insight would be appreciated.

Upvotes: 1

Views: 754

Answers (1)

James
James

Reputation: 1219

You may use MongoDB Native Driver for Node.js instead of Mongoose. I find Schema a bit easier and more-relational using Mongoose. There isn't really wrong or right in this case, however Mongoose has a bit of a performance downside as seen here: Performance

Also you can use Mongoose with mongoose-unique-validator package to deal with unique validation. Link for the package

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

var UserSchema = mongoose.Schema({
  username: { type: String, lowercase: true, required: true, unique: true},
  password: { type: String, required: true },
  email: { type: String, required: true, lowercase: true, unique: true}
});

userSchema.plugin(uniqueValidator);

Upvotes: 3

Related Questions