如何保存一个MongoDB查询,然后运行它?

我在应用程序A中加载了一个MongoDB查询。 例如:

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

…我想将其保存在DB中,并使应用程序B运行它:

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

我现在想把它保存在mongo中,并在稍后的时间检索它运行。 但MongoDB不允许我用$gte值保存文档。 我已经试过JSON.stringify(query) ,将结果string保存在数据库(好!),然后parsing它在另一边。

然后,面对ObjectId像这样string化的问题:

 { "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 } 

parsing的JSON不是有效的ObjectId。 这只是一个JS对象。

我如何保存MongoDB查询并将其parsing为mongo将再次接受的对象?

尝试使用.toString()ObjectId首先转换为string,然后在反序列化时将string转换回适当的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); 

使用MongoDB扩展JSON模块

我们不应该像对待纯Javascript对象那样对MongoDB对象进行string化和分析。

为了parsingMongoDB对象,我们必须使用Mongodb-Extended-JSON模块。 由于有些types无法parsing为纯JSON,因此Mongo将其对象转换为特殊的JSON(扩展JSON)。

应用程序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 } } 

应用程序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)