I am setting up a mongoose query where I would like to find specific records, mentioned in a custom queryObject. This queryObject contains the key-value pairs, if existent. So, if the res.query does not contain the e.g. limit, it is not added to the queryObject.
For whatever reason, the queryObject.limit parameter results in an empty array. It does filter, when entering a variable that has a number assigned, though.
This does NOT work:
const showOneMovie = async(req,res)=>{
try {
const {title, publishDate, genre, skip, sort} = req.query;
const queryObject = {};
if(title){
queryObject.title = title;
}
if(publishDate){
queryObject.publishDate = publishDate;
}
if(sort){
sort === "Ascending" ? queryObject.sort = "-title" : queryObject.sort = "title";
}
queryObject.limit = 2;
let data = await Movie.find(queryObject).limit(queryObject.limit);
res.status(200).json(data);
} catch (error) {
console.log(error)
}
}
This works:
const showOneMovie = async(req,res)=>{
try {
const {title, publishDate, genre, skip, sort} = req.query;
const queryObject = {};
if(title){
queryObject.title = title;
}
if(publishDate){
queryObject.publishDate = publishDate;
}
if(sort){
sort === "Ascending" ? queryObject.sort = "-title" : queryObject.sort = "title";
}
const limit = 2;
let data = await Movie.find(queryObject).limit(limit);
res.status(200).json(data);
} catch (error) {
console.log(error)
}
}
I know I could skip this issue, but I would really like to understand that behaviour.
2
Answers
Just because in queryParams you get String datatype for the limit and limit accept Integer.
Try to typecast the limit in first function.
In Second function you are using Integer for the limit that’s why 2nd function is working.
Credit for this answer should go to @GrafiCode but since only 1 wrong answer was posted we need a correct answer.
In your first example you have assigned a key name
limit
to thequeryObject
and have given it a value of 2:When you pass the
queryObject
to the find function here:Mongoose expects your document to have properties of
title
,publishDate
andlimit
because that’s what you added to thequeryObject
, so that’s what it thinks you’re looking for (sort ignored for now). YourqueryObject
might look something like this:What mongoose then executes is this:
Since your Schema does not contain a property of
limit
, mongoose doesn’t find anything.In your second example, you don’t add
limit
to thequeryObject
and instead create a lexical scoped variabeconst limit = 2;
that is not part of the query until it’s used to limit the results.