1

I am finding one single document using findOne() My document has userid as one of the key inside my users model.

Example

{
   userid: 1,
   name: 'John'
}

Now I am able to receive this document as object when I do the following

users.findOne({userid: 1}, function(e, data){
   if(e){
      return (res.send('Failed'))
   }else{
      return (res.send(data))
   }
});

However, if I try to submit the same value of userid dynamically then the data obj returns null and still if(e) statement is not executed.

Example

users.findOne({userid: req.body.userid}, function(e, data){
   if(e){
      return (res.send('Failed'))
   }else{
      return (res.send(data))
   }
});

I console logged the value of req.body.userid and checked that it is 1 when I pass it dynamically.

What am I doing wrong? Is the value of req.body.userid not passed correctly to userid key?

1 Answer 1

3

If you are trying to pass filter values using variables you need to set it correctly using a filter object

Check the code below

var key = "userId"; //example
var value = req.body.userId;
var filter = {};
filter[key] = value;

    user.model.findOne(filter, function(e, data){
       if(e){
          return (res.send('Failed'))
       }else{
          return (res.send(data))
       }
    });
Sign up to request clarification or add additional context in comments.

6 Comments

Now if(e) executed and the error says i have a cast error."name": "CastError", Also, i have made sure that the value of req.body.userid is integer.
console.log the value of req.body.userid, typeof req.body.userid and parseInt(req.body.userid) to be able to see what is coming from the request and the type of userid ... because the error means that the parseInt function result is NAN which means the req.body.userid is not a number string or even a number
The exptected type of userid in the document is number and the typeOf req.body.userid is also a number.
But how parseInt return NAN if its a number ? ...i can't see any possible error in your code other than that .... maybe the value you are logging is different from the one you pass to findOne filter ? maybe you have a typo ? as if its a number it should parseInt correctly
Probably your variables are not passed correctly to filter ... i updated the answer ... i think this should work for you ... just add the correct values in filter object based on your real code
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.