【问题标题】:Mongoose: Search for documents with specified id in the populated documentMongoose:在填充的文档中搜索具有指定 id 的文档
【发布时间】:2012-05-11 19:18:38
【问题描述】:

在 Mongoose 中,我有两个 Schema,它们使用 Mongoose populate 链接:

var SystemSchema = new Schema({
    name                    : {type : String, trim : true}
    , hosts                 : [{ type: ObjectId, ref: 'Host' }]
});

var HostSchema = new Schema({
    name                    : {type : String, trim : true}
});

我的问题:我有一个主机的给定 ObjectId,现在想查看哪些系统确实引用了该主机。

我这样做是因为我通常只访问 SystemsSchema 并希望填充主机,但有人问我是否也可以检查主机的系统。现在我尝试简单地搜索而不是从主机填充到系统,但我有点卡住了。

我的一个尝试是搜索 where,但这没有成功:

System.where('hosts').in(['4fabca804c9d76ac0b000022']).run(function(err, hosts) {
        console.log(hosts);
    });

有没有这样的搜索方式?请不要告诉我简单地将 HostSchema 作为子文档放入 SystemSchema,这只是一个简化的示例。

提前致谢!

最好的问候, 乌力

【问题讨论】:

    标签: node.js search document mongoose populate


    【解决方案1】:

    我想你错过了.populate

     System
        .find({ hosts : '4fabca804c9d76ac0b000022' })
        .populate('hosts')
        .run(function(err, systems) {
             console.log(systems);
        });
    

    【讨论】:

    • 谢谢,我以某种方式混合了一些 id,上面的查询现在也可以正常工作。我只需要上面的信息,因此没有主机。感谢您的回答!
    猜你喜欢
    • 2014-08-06
    • 2018-08-16
    • 1970-01-01
    • 2020-12-08
    • 2017-01-27
    • 1970-01-01
    • 2020-10-22
    • 2013-08-15
    • 2014-08-16
    相关资源
    最近更新 更多