Reputation: 404
I'm using NodeJS with Mongoose.
const payload = {
id,
email,
password: md5(password)
}
User.create(payload, async(error, result) => {
// DO SOMETHING
})
I'm looking the best way to check if id and email doesn't already exists before to create a new document on my collection.
Upvotes: 0
Views: 607
Reputation: 480
You have to make a call first on the DB to check for the email.
The actual code in nodejs would look something like this:
mongo.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
}, async (err, client) => {
if (err) {
console.error(err);
return;
}
db = client.db('a_db');
const payload = {
id: 'some_id',
email: '[email protected]',
password: md5('password')
}
db.collection('users').findOne({email: payload.email}, (err, buffer) => {
buffer.toArray((err, res) => {
if (res) console.log('user already in')
else{
db.collection('users').insertOne(payload, (err, res) => {
// DO SOMETHING
});
}
});
});
});
On the other hand you should never use md5 for hashing your passwords because it has being broken. You should us at least sha512.
Upvotes: 1