You can’t pass mongo a string as in the following below with single quotes at the beginning and end. You can’t parse the object.
Hi Michael,
The MongoDB Node.JS driver find() method expects not a string, but a query object (JSON). This means that you would need to convert the string into JSON first before passing it through.
Usually a pure JSON string can be parsed utilising JSON.parse(). However, your example query string contains JavaScript statement i.e. new Date()
which can’t be handled by JSON.parse()
.
I’d recommend to change the format of your string to be in MongoDB extended JSON strict mode. For example, your query string would be:
'{ "started": { "$gte": {"$date": "2016-01-01T00:00:00.000Z"}, "$lt": {"$date":"2016-01-02T00:00:00.000Z"}}}'
You can then utilise npm
module mongodb-extended-json to parse this into JSON. for example:
var extJSON = require("mongodb-extended-json");
var query = extJSON.parse('{ "started": { "$gte": {"$date": "2016-01-01T00:00:00.000Z"}, "$lt": {"$date":"2016-01-02T00:00:00.000Z"}}}');
db.collection.find(query);
See also Node.JS driver quick-start for more information.
I want something akin to a stored procedure in SQL server where I can pass parameters and plug them and run. What is available? Any other approach?
You can also write a JavaScript function that you could call in your Node.Js script (client side). Invoke the function and pass parameters to it, which wraps the query.
Regards,
Wan.