Caio Paes
Caio Paes

Reputation: 81

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?

Upvotes: 2

Views: 1506

Answers (2)

Caio Paes
Caio Paes

Reputation: 81

Use MongoDB Extended JSON module

We shouldn't stringify and parse MongoDB Objects as if they are pure Javascript Objects.

To parse MongoDB Objects we have to use Mongodb-Extended-JSON module. Since there are some types that can not be parsed to pure JSON, Mongo translates Its objects to a special JSON (Extended JSON).

Solution

On Application A:

const EJSON = require('mongodb-extended-json')
const query = { country: new ObjectId(""), age: { $gte: 25 } }
const strQuery = EJSON.stringify(query)
// { "country": { "$oid": "5422c2e6e4b02fd68a01225c" }, "age": { "$gte": 25 } }

On Application B:

const EJSON = require('mongodb-extended-json')
const query = EJSON.parse(strQuery)
const query = EJSON.stringify(query)
// query is now a MongoDB Object that can be used on db.collection('foo').find(query)

Upvotes: 2

vesse
vesse

Reputation: 5078

Try converting the ObjectId to string first with .toString(), and then when deserializing convert the string back to a proper ObjectId:

const ObjectId = require('mongodb').ObjectId;

let query = {
  country: new ObjectId('590a0953ca81dd490ee8dba3'),
  age: {
    $gte: 25
  }
};

query.country = query.country.toString();
const serialized = JSON.stringify(query);

console.log(serialized);

let deserialized = JSON.parse(serialized);
deserialized.country = new ObjectId(deserialized.country);

console.log(deserialized);

Upvotes: 1

Related Questions