Reputation: 494
I would like to get information if selected user email & name already exist somewhere in MongoDB database. I want to make email and name unique, therefore it couldn't be duplicates of both those values.
I already wrote working code, but I would like to know if this solution is optimal.
User.find({ email: email })
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: 'Mail exists'
})
} else {
User.find({ name: name })
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: 'Name exist'
})
} else {
// SOME CODE HERE
}
})
}
})
Is there any shorter way to write this? Thanks :)
Upvotes: 0
Views: 428
Reputation: 1218
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.
Upvotes: 1
Reputation: 1274
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}]}
Upvotes: 0
Reputation: 3571
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.
Upvotes: 1