[英]check if already exists field before to create a document on MongoDB / NodeJS
I'm using NodeJS with Mongoose .我将NodeJS与ZCCADCDEDB567ABAE643E15DCF0974E503Z一起使用。
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.我正在寻找最好的方法来检查id和email在我的收藏中创建新文档之前是否不存在。
You have to make a call first on the DB to check for the email.您必须先在数据库上拨打电话以检查 email。
The actual code in nodejs would look something like this: nodejs 中的实际代码如下所示:
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: 'some_email@email.com',
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.另一方面,你永远不应该使用 md5 来散列你的密码,因为它已经被破坏了。 You should us at least sha512.您至少应该使用 sha512。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.