【问题标题】:How to save a MongoDB Query and run It afterwards?如何保存 MongoDB 查询并在之后运行它?
【发布时间】:2017-10-01 15:58:47
【问题描述】:

我在 Application A 中安装了一个 MongoDB 查询。例如:

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

...我想将它保存在 de DB 中并让 Application B 运行它:

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

我想现在将它保存在 mongo 中,并在以后检索它以运行。但是 MongoDB 不允许我保存具有 $gte 值的文档。我已经尝试JSON.stringify(query),将结果字符串保存在数据库中(好的!),然后在另一边解析它。

然后,遇到ObjectId 像这样被字符串化的问题:

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

解析的 JSON 不是有效的 ObjectId。它只是一个 JS 对象。

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

【问题讨论】:

    标签: json node.js mongodb


    【解决方案1】:

    尝试先用.toString()ObjectId转换为字符串,然后在反序列化时将字符串转换回正确的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);
    

    【讨论】:

    • 感谢您的回答,@vesse!我发布了这个问题,因为我在这个问题上挣扎了好几天。然后,我找到了解决方案。您的解决方案使用 ObjectId 解决简单查询的问题,但我们必须处理更复杂查询中的每个 ObjectId,例如:`{ country: { "$in": [ObjectId1, ObjectId2, ...] }.
    【解决方案2】:

    使用MongoDB Extended JSON module

    我们不应该将 MongoDB 对象作为纯 Javascript 对象进行字符串化和解析。

    要解析 MongoDB 对象,我们必须使用 Mongodb-Extended-JSON 模块。由于有些类型无法解析为纯 JSON,Mongo 将其对象转换为特殊的 JSON(Extended 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)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    相关资源
    最近更新 更多