user287332 user287332 - 6 months ago 13
Node.js Question

Unable to do find using variable in query

I was working on a project on windows on NodeJS.

I used the following code for checking login credentials. It was working fine till I changed to ubuntu 16.04 .

I set up my environment and now the variables are not being treated as strings.

It's returning empty set from the DB. If I do it like this

user_name:"some user name",password:"some password"
, it's working fine.

Please help. I am stuck bad :-( sorry if its a noob type mistake :-)

app.post('/login', function(req, res, next) {
var N1 = req.body.N1;
var N2 = req.body.N2;
console.log(N1+N2);//Getting passed successfully
MongoClient.connect(url, function(err, db) {
if (err) {
throw err;
console.log("into connectivity error");
}
console.log(N1);
db.collection('col.login').find({user_name:N1,pass:N2}).toArray(function(err, result) {
if (err) {
throw err;
}
resultArray=result;
try{
req.session.userId = result[0]._id;
req.session.userType = result[0].type;
req.session.userComp = result[0].comp_id;
req.session.cat = -1;
if(result[0].type=="root") {
res.redirect('/New_Company');
}


database structure:

{
"_id" : ObjectId("xxxxxxxxxxxxxxxxxxx"),
"user_name" : "xxxxxxx",
"pass" : "xxxxx",
"type" : "root",
"email" : "xxxx@gmail.com",
"comp_name" : "NULL",
"default_page" : "main",
"name" : "xxxxx",
"comp_id" : "NULL"
}

Answer

Do the following way :-

app.post('/login', function(req, res, next) {
var N1 = (req.body.N1).toString();//Do toString()
var N2 = (req.body.N2).toString();
console.log(N1+N2);//Getting passed successfully
MongoClient.connect(url, function(err, db) {
    if (err) {
        throw err;
        console.log("into connectivity error");
    }
    console.log(N1);
    db.collection('col.login').find({user_name:N1,pass:N2}).toArray(function(err, result) {
        if (err) {
            throw err;
        }
        resultArray=result;
        try{
            req.session.userId = result[0]._id;
            req.session.userType = result[0].type;
            req.session.userComp = result[0].comp_id;
            req.session.cat = -1;
            if(result[0].type=="root") {
                res.redirect('/New_Company');
            }
      });

Refer toString for more info on toString().