简体   繁体   English

检查之前是否已经存在字段以在 MongoDB / NodeJS 上创建文档

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

I'm using NodeJS with Mongoose .我将NodeJSZCCADCDEDB567ABAE643E15DCF0974E503Z一起使用。

    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.我正在寻找最好的方法来检查idemail在我的收藏中创建新文档之前是否不存在。

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.

相关问题 POST之前如何检查数据库中是否已存在文档-MongoDB,NodeJS - How to check for document already in database before POST - MongoDB, NodeJS 无法使用NodeJ检查MongoDB上是否存在字段 - Unable to check if field exists on MongoDB using NodeJs 如果没有创建文档,请检查文档是否已存在 - Check if document already exists if not create one 如何检查具有某些字段的文档是否已存在于 MongoDB 数据库中? - How to check if document with certain fields already exists in the MongoDB database? 检查文档是否已经存在,如果是,则进行更新,否则创建新的-猫鼬 - Check if document already exists and if yes then update, otherwise create new - Mongoose Mongodb 检查数组的子文档中是否存在字段 - Mongodb check If field exists in an sub-document of an array 更新文档中的嵌入式数组(如果存在),否则创建一个新文档MongoDB NodeJS - Update an embedded array inside an document if it exists otherwise create a new document MongoDB NodeJS 如何创建新文档(如果不存在)并使用MongoDB NodeJS本机驱动程序返回新文档 - How to create a new document 'if not exists' and return the new document with MongoDB NodeJS native driver Nodejs,AWS Dynamodb如何在创建新记录之前检查用户是否已经存在 - Nodejs , AWS Dynamodb how to check if user already exists before creating new record 更新mongodb文档,如果文档存在,否则创建 - Update mongodb document, if the document exists, else create
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM