【发布时间】: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