简体   繁体   English

猫鼬在引用的子文档数组中查找

[英]Mongoose find in array of referenced subdocuments

I am trying to find certain visits coming from an ip.The visits schema looks like this : 我正在尝试查找来自ip的某些访问。访问模式如下所示:

var VisitSchema = new Schema({
visitId:        String,
ip:             [{ type: Schema.Types.ObjectId, ref: 'VisitorIp' }]
});
mongoose.model('Visit', VisitSchema);

the ip schema looks like this : ip模式如下所示:

var VisitorIpSchema = new Schema({
ip:             String,
country:        String
});
mongoose.model('VisitorIp', VisitorIpSchema);

when i try to run the normal find for a specific ip : 当我尝试运行特定IP的正常查找时:

Visit.find({ip.ip:myIp}))
.populate('ip')
.exec(function(err, visits){
  console.log(visits)
})

it returns an empty array. 它返回一个空数组。 All the recordings in the mongo database look and behave normally. mongo数据库中的所有记录外观和行为均正常。

Please help I have run out of ideas. 请帮助我用尽了所有想法。

One not-so-elegant approach that you can take is to query after populating, ie get all the visits, populate the visits' ip documents with a query filter and when the query executes you'll then need to manually filter out visit documents that don't have any IP docs that matched the populate criteria, something like: 您可以采用的一种不太优雅的方法是在填充后进行查询,即获取所有访问,使用查询过滤器填充访问的ip文档,然后在执行查询时需要手动过滤出没有任何符合填充条件的IP文档,例如:

Visit.find({})
    .populate('ip', null, { "ip": myIp } )
    .where('ip.ip').equals(myIp) /* where('ip.ip').in([myIp]) */
    .exec(function(err, visits){
        visits = visits.filter(function(doc){
            return visits.ip.length;
        })
        // do stuff with visits
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM