1

I'm trying to do a find query using a string and a number as fields. The query works while looking for the string alone. How can I make it work for number as well?

var check = request.body.cookie; // String
var tok = request.body.token; // It's a number

db.collection("users").find({'name':check, 'token':tok}).toArray(function(err, rows) {
    if(!rows.length)    
    {
    console.log("No data found");
    }
});

A sample collection is given below

> db.users.find()
{ "_id" : ObjectId("608be0dc8b83df0248ed2fc1"), "name" : "John", "age" : "18", "gender" : "M", 
"country" : "RR", "socketid" : "1",
"token" : "5907" }
3
  • What do you get when you try console.log(typeof request.body.token); Commented Apr 30, 2021 at 14:00
  • I deleted accidentially a curly bracket after the if statement - unforunately the edit queue is full... Commented Apr 30, 2021 at 17:14
  • @biberman corrected!! Commented Apr 30, 2021 at 21:46

2 Answers 2

2

You can use expression $expr condition to make sure hundred percent whatever token has type string or number,

  • $toInt to convert string to number
var check = request.body.cookie; // String
var tok = request.body.token; // It's a number

db.collection("users").find({
  $and: [
    { name: check },
    {
      $expr: {
        $eq: [{ $toInt: "$token" }, tok]
      }
    }
  ]
}).toArray(function(err, rows) {
    if(!rows.length)    
        console.log("No data found");
    }
});

Playground

Sign up to request clarification or add additional context in comments.

Comments

2

The token field is probably stored as a string in the database, not as a number. Look at the commas.

"token" : "5907"  

Try converting tok to a string in the query.

find({'name':check, 'token':String(tok)})

1 Comment

This works as well. A simple fix!! Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.