0

I'm trying use find function to get data from my DB in mLab. I wrote this code, but I am getting an empty string. My schema had id, name, course and grade. It works for me when I want the file of the name but not for id. I guess it's because of the extra _id files that the mLab adds. How do I fix it to get back the JSON that fits the id (let's say id=1)?

     app.get('/getStudentById/:id', function(req, res) { //else if url path is getStudGrade with id param
         Stud.find({id:req.params.id}, function(err, user){
            if(err) throw err;
            res.json(user);
           mongoose.disconnect();
         });
     })

new edit

I have changed the filed 'id' to 'idStudent' in my DB and now it working.

Stud.find({ idStudent: req.params.id)}...)

but why?

6
  • what is the type of id field example (string, number), and how you send the request. Commented May 13, 2016 at 9:55
  • how you send the request to fetch the getStudentById Commented May 13, 2016 at 10:02
  • using get and sending it in the url localhost:3000/getStudentById/1 Commented May 13, 2016 at 10:03
  • your code is perfect, just check the id is available or not in database that you are passing in request. Commented May 13, 2016 at 10:10
  • mongoose create _id field automatically. Remove id field from your schema and then apply condition with _id. Commented May 13, 2016 at 10:14

2 Answers 2

1

So, assuming req.params.id actually has a value and /getAll shows that all your records have an id field set, the only thing that jumps out to me is the fact that your comparing a string to a Number i.e. req.params.id will be a string after deserialization but your schema dictates that the id field is numeric.

I am not sure if mongoose uses coercive comparison i.e. == over === (I doubt it), so in order to be more accurate you should parse your string to Number then do the comparison e.g.

Stud.find({ id: parseInt(req.params.id)}, ...)
Sign up to request clarification or add additional context in comments.

1 Comment

When I do that it doesn't work.. but if I change id to String it does... Do you know why?
0

Functions in query clause might not work, so to convert to Number just do:

Stud.find({ id: 1*req.params.id}, ...)

Comments

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.