I need to send a mongo query in JSON typed request body, something like:
{ _id : { $gt : ObjectId("575d0c22964ddb3b6ba41bed") } }
(to get records inserted later than the id'ed record)
On the node server side I have express with body-parser middleware. It won't parse the request body JSON unless everything is quoted. E.g. the above has to be like:
{ "_id" : { "$gt" : "ObjectId(\"575d0c22964ddb3b6ba41bed\")" } }
The db runs the query with all the quotation marks and returns nothing.
How do I pass ObjectId() to mongodb as a function without re-parsing the whole request body and stripping off the quotation marks?
I'm testing with postman extension in Chrome, and sends the request to a REST url: /api/:obj_type/list.
The entire request body is used as a query.
you would be only passing around the string value in the client and server until a request is made the the database at which point you would make it a new ObjectID with the same value to be passed into the db. Passing around a string is a bit easier as all the clients/server know how to deal with a string vs ObjectID - also passing the ObjectID in a URL would be an issue. - To answer your question on how to pass the ObjectID() to Monogdb without re-parsing. You really wouldn't unless I'm misunderstanding the context
but pass around the ID as a string so it would be something like var stringId = "507f1f77bcf86cd799439011" and when you are about do a query you would do something along the lines of col.find({_id: new ObjectId(stringId)}).toArray(function(err,results){});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With