【问题标题】:Is there an option to find exact match of data and && condition in MongoDB是否可以在 MongoDB 中找到完全匹配的数据和 && 条件
【发布时间】:2021-05-24 20:58:11
【问题描述】:

我有一个登录表单。我已经将我们的用户信息存储在 MongoDB Atlas https://www.mongodb.com/cloud/atlas/

我的数据是这样的

    _id:60a64bee48f6eed16a566cf5
    user_name:"test1"
    user_password:"123456"

    _id:60a64bee48f6eed16a566cf5
    user_name:"test2"
    user_password:"abcdef"

   _id:60a64bee48f6eed16a566cf5
    user_name:"test3"
    user_password:"123456"

我应该检索 user_name 和 user_password 都匹配的数据。

我的代码是

app.post('/login', (req, res) => {
 let userName = req.body.user_name;
 let userPassword = req.body.user_password;
 userCollection.find({user_name: userName}).toArray()
 .then(results => {
    console.log('success');
    res.redirect('/')
    // console.log(results)
 })
 .catch(err => {
    console.error(error)
 })
})

我的问题是找到与数据匹配的文档的任何其他选项就像给定的用户名和用户密码应该匹配

感谢您的建议。

【问题讨论】:

    标签: node.js mongodb express mongodb-atlas


    【解决方案1】:
    • 试试这个代码,它似乎很容易理解验证密码和用户名

       userCollection.find({user_name: userName},function(err,foundUser){
      
                   if(!err){
                      if(foundUser.userPassword == userPassword){
                       console.log('success');
                        res.redirect('/');
      
                      }
      
                 }
                  else{
                console.log(err);
      

    }

    });

    
     - 
    

    【讨论】:

      【解决方案2】:

      使用下面的查询

      userCollection.find( { $and: [ {user_name: userName, user_password: userPassword } ] } )
      

      我们不应该将密码直接存储在您的数据库中,您应该首先使用任何加密库对密码进行加密,然后将其存储在数据库中

      【讨论】:

        【解决方案3】:

        使用

        userCollection.find({user_name: userName, user_password: userPassword })
        

        您可以使用findOne 代替find

        https://docs.mongodb.com/drivers/node/usage-examples/findOne/

        userCollection.findOne({user_name: userName, user_password: userPassword })
        

        注意:- 不要存储原始密码,存储散列密码

        您可以使用https://www.npmjs.com/package/bcrypt 对密码进行哈希处理。

        【讨论】:

        • 明白。谢谢。
        • 感谢您的建议。你能给出实现 findOne 的示例代码吗?我不知道如何应用这个。
        • @MuthulakshmiM 更新答案
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-22
        • 1970-01-01
        • 2020-06-18
        • 1970-01-01
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多