How To Check If Selected Email & Name Is Alread Exist In Mongodb
Solution 1:
Case 1 - You need the pair to be unique
In this case the pair (email,name) will be unique. This can be done using AND query.
User.find({email:email,name:name})
Case 2 - You do not need either email or name appear twice
This can cause some issues since there can be two people with same name but different email. This condition can be met using OR querying.
User.find({$or:[{email:email},{name:name}]}
Personal recommendation : Follow the solution given by @will-alexander It will be more efficient.
Solution 2:
If you are using Mongoose, you can achieve this from within the Model using mongoose-unique-validator
:
const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');
const userSchema = mongoose.Schema({
email: { type: String, required: true, unique: true },
name: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
userSchema.plugin(uniqueValidator);
module.exports = mongoose.model('User', userSchema);
This way, if Mongoose detects you trying to add a User with an existing name or email, it will throw an error.
Solution 3:
If you want uniqueness on both the keys use in one query
User.find({email:email,name:name})
If you want both keys to be separately unique use in one query
User.find({$or:[{email:email},{name:name}]}
Post a Comment for "How To Check If Selected Email & Name Is Alread Exist In Mongodb"