如何使用Mongoose取消引用Mongoengine创建的Object



我用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')

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

在您的模式中必须更改此类型:

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

在引用部分要小心,它必须是你给机器引用模式的名称,例如machine。别忘了用引号把它括起来。希望它能解决问题。

最新更新