Wednesday 3 May 2017

How to save a MongoDB Query and run It afterwards?

I am mounting a MongoDB Query in Application A. For example:

const query = { country: new ObjectId(""), age: { $gte: 25 } }
// save contents of 'query'

... And I want to save It in de DB and make the Application B run It:

// const query = read object from the database
db.collection('foo').find(query).toArray()...

I want to save It in mongo now and retrieve It in a later period to run. But MongoDB doesn't allow me to save a document with $gte value. I've already tried to JSON.stringify(query), save the result String in the DB (Ok!) and then parse It on the other side.

Then, faced the problem where the ObjectId gets stringified like this:

{
    "class" : "org.bson.types.ObjectId",
    "counter" : 9053980.0,
    "date" : "2015-04-01T19:24:39Z",
    "machineIdentifier" : 14987412.0,
    "processIdentifier" : 29601.0,
    "time" : 1427916279000.0,
    "timeSecond" : 1427916279.0,
    "timestamp" : 1427916279.0
}

The parsed JSON is not a valid ObjectId. It's just a JS Object.

How can I save the MongoDB Query and parse It to an object that mongo will accept again?



via Caio Paes

No comments:

Post a Comment