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();
});
})
I have changed the filed 'id' to 'idStudent' in my DB and now it working.
Stud.find({ idStudent: req.params.id)}...)
but why?
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
ie 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 ie ==
over ===
(I doubt it), so in order to be more accurate you should parse your string to Number
then do the comparison eg
Stud.find({ id: parseInt(req.params.id)}, ...)
查询子句中的函数可能不起作用,因此将其转换为Number
即可:
Stud.find({ id: 1*req.params.id}, ...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.