【问题标题】:How to dereference Object created by Mongoengine using Mongoose?如何取消引用 Mongoengine 使用 Mongoose 创建的对象?
【发布时间】:2019-01-13 03:46:10
【问题描述】:

我用 Python 编写了许多脚本,这些脚本从各种来源收集数据,并使用 Mongoengine 跨 3 个不同的集合将其转储到 MongoDB 中。其中一个集合的文档(接口)引用了另外两个集合(v_machines、p_machines)之一中的文档,这些集合托管了不同的数据模式。作为 nodejs 的初学者,我不确定在使用 Mongoose 时如何取消引用。

我尝试使用 populate() 方法,但很快返回以下错误:

{
    "statusCode": 500,
    "error": "Internal Server Error",
    "message": "Cast to ObjectId failed for value \"Machine\" at path \"_id\" for model \"interfaces\""
}

使用 MongoEngine 中的 GenericReferenceField,模式示例如下所示:

{
    "_id" : ObjectId("8c49db2f45546d3a586877a6"),
    "name" : "testbox.blah.com",
    "mac_address" : "c4:cc:fa:bd:49:66",
    "label" : "eth0",
    "machine_reference" : {
        "_cls" : "Machine",
        "_ref" : {
            "$ref" : "p_machines",
            "$id" : ObjectId("5c32cb2f46546c4a586877a5")
        }
    }
}

这看起来与我看到的使用 .populate() 的示例有点不同。我的搜索中没有“_cls”参考。看来我必须再下一层才能获取数据。

在我的 js 代码中,我将模型定义为:

const interface_schema = new mongoose.Schema({
  id: {type: mongoose.Schema.Types.ObjectId, index: true, required: true},
  machine_reference: {type: mongoose.Schema.Types.Mixed, index: true, required: true},
  name: {type: String, index: true, required: true},
  mac_address: {type: String, required: true},
  label: {type: String, required: true},
})

此处查询代码:

interfaces.find({ 'name': req.query.name }).populate('machine_reference')

我希望能够取消引用两个集合的相应文档。我该怎么做呢?接受建议,甚至重新创建架构或更改模型。

【问题讨论】:

    标签: node.js mongoose mongoengine


    【解决方案1】:

    在您的架构中必须更改此类型:

    machine_reference: {type: mongoose.Schema.Types.ObjectId, index: true, required: true, ref:'name of the model'}
    

    在 ref 部分要小心,它必须是您为机器引用模式指定的名称,例如机器。不要忘记用引号括起来。希望能解决问题。

    【讨论】:

    • 感谢您的快速回复!看起来那不起作用,我返回了同样的错误。在相关说明中,我的 machine_reference 键引用 Machine 或 vMachine 集合。以这种方式设置它不会只允许我取消引用“Machine”而不是“vMachine”吗?
    猜你喜欢
    • 2016-02-06
    • 2016-04-07
    • 1970-01-01
    • 2018-05-08
    • 2014-04-10
    • 2019-06-05
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多