I'm trying to write a Node.js web API using Express and MongoDB. I'm dynamically parsing the req.query object (Express's querystring storage/parser) from a GET request and updating an object called "query" with the the querystring pairs so I can find documents in the database collection that match whatever the querystring parameters are. For example, a
localhost:3000//users?name=John&last=Smith will modify the query object so that we find only records that have a name field as John and a last field as Smith. We could also send none of those parameters, only one, or more. The problem is when I try to send a querystring like this:
localhost:3000//users?_id=1
This returns nothing. When I use the terminal (windows cmd) to directly access the database and run this query (db.Users.find({_id : 1})) it works fine and returns as expected. Further, console.log(query._id) returns 1, so I know that the object is storing the parameter as I expect.
var query = {};
//Iterate through query string parameters as a Get request
//Add them to the query object, (add them as object properties)
for(var propName in req.query) {
query[propName] = req.query[propName];
}
db.collection("Users", function(err, collection) {
if(!err) {
collection.find(query, {limit: 100},function(err, cursor) {
if(!err) {
cursor.toArray(function(err, arr) {
if(!err) {
console.log(arr);
res.send(arr);
} else {
console.log("Failed to turn cursor to array: "+err);
}
});
} else {
console.log("Find failed: "+err);
}
});
} else {
console.log("Failed opening collection: "+err);
}
});
This is because the _id value in your MongoDB document is the number 1 but you're querying for it using the string '1' (all req.query fields are strings).
Possible solutions would be to parse the field into a number:
if (propName === '_id') {
query[propName] = parseInt(query[propName], 10);
}
Or to use something like Mongoose which will do this sort of casting for you based on a schema definition.