Reputation: 1560
I've successfully queried what I'm trying to in the mongo CLI, with the following query.
db.catches.find({'weightTotal': {'$gte' : 150} })
However, when I try to send a query up from angular to the route as such (with a little more specificity):
Hatchery.getByLocation(
{
'x': $scope.y.x._id,
'city': place.data[0].city,
'weightTotal': {'$gte' : 150 }
})
I get the usual error when something blows up in mongoose:
TypeError: Cannot call method 'toString' of undefined
at ServerResponse.writeHead (http.js:1180:45)
at ServerResponse.writeHead (/Users/ShiftedRec/x/y/node_modules/express-session/node_modules/on-headers/index.js:53:19)
But more specifically (console logging the error)
{ message: 'Cast to number failed for value "{"$gte":150}" at path "weightTotal"',
name: 'CastError',
kind: 'number',
value: '{"$gte":150}',
path: 'weightTotal' }
I've gotten this to work by doing a .where
in the route, but I'd rather fit everything in the query. It can keep my routes cleaner if I just pass what I need to into a query instead of doing conditional where statements based on permissions etc.
The route the query is passed to looks like this:
router.get('/', function (req, res, next) {
User
.find(req.query)
.populate('post')
.exec(function (err, data){
if (err) return next(err);
res.json(data);
});
});
req.query console logs into this:
{ x: '5581efdcc465c1ccd97a1f6b',
y: '5581efe2458256f5d9848ca7',
weightTotal: '{"$gt": 150}' }
I'm using Mongoose 4.0.1. Any ideas?
Upvotes: 2
Views: 501
Reputation: 225
GET requests queries are strings, so if you send this:
www.mysite.com/?data=1&weightTotal=5
You will get this (strings and not numbers):
{data: "1",
weightTotal: "5"}
In order to use the data you can parse it somehow, for example:
req.query.weightTotal = JSON.parse(req.query.weightTotal);
or if it's just a number, a faster parse is:
req.query.weightTotal = +req.query.weightTotal;
A smarter solution, if you are sending objects in your requests, will be to use POST and not GET.
Upvotes: 1
Reputation: 103345
Try converting the req.query.weightTotal
string to an object first:
req.query.weightTotal = eval('(' + req.query.weightTotal + ')');
Check the demo below.
var obj = {
x: '5581efdcc465c1ccd97a1f6b',
y: '5581efe2458256f5d9848ca7',
weightTotal: '{"$gt": 150}'
}
obj.weightTotal = eval('(' + obj.weightTotal + ')');
pre.innerHTML = JSON.stringify(obj);
<pre id="pre"></pre>
Upvotes: 0