简体   繁体   中英

check if already exists field before to create a document on MongoDB / NodeJS

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.

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: '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. You should us at least sha512.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM