如何在mongoDB中比较输入和文档

时间:2019-05-28 10:44:53

标签: node.js mongodb express

当我注册[向DB输入电子邮件/密码]成功时。然后,我要登录。如果输入[email / pass] ==集合中的文档>>转到下一页,否则console.log ['错误的email / pass']

我尝试写IF / else代码,但我不知道检查条件。

此代码是注册表格

app.post('/register',function(req,res){
    MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");
  let myobj = { Email: req.body.email, Password: req.body.psw } ;

  dbo.collection("Register").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log(" document inserted");
    db.close();
  });
});

});

此代码是登录表单

app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;

  let dbo = db.db("project");

  let cursor = dbo.collection('Register').find();
   cursor.each(function(err,doc) {
    if (doc == req.body.email && req.body.psw){
      console.log("goto next page");

    }
    else{
      console.log('wrong');
    }

   });
    db.close();
  });
});

正确输入和错误输入输出=错误

请插入循环检查所有数组pls。

app.post('/index',function(req,res){

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("project");

  dbo.collection("Register").findOne({}, function(err, result) {

    if (result.Email == req.body.email && result.Password == req.body.psw) {
      console.log("OK");
    }
    else{
      console.log(result.Email && result.Password);
    }
    db.close();
  });
});
});

2 个答案:

答案 0 :(得分:1)

您必须比较各个值,例如:

if (doc.Email == req.body.email &&  doc.Password == req.body.psw){
  console.log("goto next page");

}

答案 1 :(得分:0)

首先,您应该检查有效的请求正文,并且应该执行var List1 = [{id : "idValue2"}, {id : "idValue5"}] var List2 = [ {code : "idValue1", label: "value1"}, {code : "idValue2", label: "value2"}, {code : "idValue3", label: "value3"}, {code : "idValue4", label: "value4"}, {code : "idValue5", label: "value5"} ] var result = []; var copyList2 = List2; for(var i = 0; i < List1.length; i++){ for(var j = 0; j < List2.length; j++){ if(List1[i].id === List2[j].code){ result.push(List2[j]); copyList2.splice(j, 1); } } } result = result.concat(copyList2); console.log(result);查询,而不是运行fineone并进行检查。请参阅以下更正的内容:

for-loop