猫鼬查询需要填充的数据

Mongoose querying data that needs populating

我有一个非常简单的 Mongoose 模型:

aclSchema = mongoose.Schema({
    _id: String,
    public_read: Boolean,
    public_write: Boolean,
});
aclModel = mongoose.model('acl', aclSchema);

以及引用它的另一个模型:

thingSchema = mongoose.Schema({
    _id: String,
    _acl: { type: String, ref: 'acl' }
});
thingModel = mongoose.model('thing', thingSchema);

我需要能够找到 _acl.public_read 为真的文档 ( thingModel )。我遇到的问题是,由于 thing._acl 是一个 ref,它在查询完成后才会被填充。

示例:

thingModel.find({"_acl.public_read":true}).populate('_acl').exec(callback);

returns 没有结果,因为我猜 _acl 是一个引用,直到找到 returns 文档后才会填充它。

附带说明一下,架构比这更复杂,并且其中有其他可能是循环的引用。为简单起见,我没有包括它们,但基本思想就在那里。如果真的这么简单,我会使用子文档,它会按预期工作。

有没有更好的方法可以让我得到预期的文件?

您现在可以在 Mongo 3.2 中使用 $lookup

$lookup 有四个参数

from:指定同一个数据库中的集合来执行连接。来自集合无法分片。

localField:指定从文档输入到 $lookup 阶段的字段。 $lookup 对 from 集合的文档中的 localField 与 foreignField 执行相等匹配。

foreignField:指定from集合中文档的字段。

as:指定要添加到输入文档的新数组字段的名称。新数组字段包含 from 集合中的匹配文档。

thingModel.aggregate([{

  $lookup: {
     from: 'aclCollection',
     localField: '_acl',
     foreignField: '_id',
     as : 'acl'
  },
  {$unwind: '$acl'},
  {$match:{"acl.public_read":true }}
], callback);

如果是populate,直接是不行的。参考类似问题 Mongoose nested query on Model by field of its referenced model