使用匹配填充查询返回null

时间:2015-05-12 21:45:20

标签: mongodb mongoose

我有三个模式,需要它们分开,我不能使用子文档。重要的是这个

export var TestSchema = new mongoose.Schema({
    hash: { type: String, index: { unique: true }, default: common.randomHash },
    date: { type: Date, default: Date.now },
    result: { type: Object },
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    data: { type: Object },
    finished: Date,
    lang: { type: String, default: 'pt' },
    benchmark: { type: String, required: true },
    order: { type: mongoose.Schema.Types.ObjectId, ref: 'Transaction' },
    /* TODO: remove */
    name: { type: String } 
});

我有一个查询来填充(它实际上是一个分页助手,但我正在追逐):

TestModel.find({hide: {$ne: true}, user: id}).populate({
   path: 'user', 
   match: {$or: [
     {email: new RegExp(search, i)},
     {name: new RegExp(search, i)}, 
     {empresa: new RegExp(search, i)},
   ]}
}).exec().then(/*...*/)

当populate.match找不到任何内容时,它会将user设置为null。我尝试设置find({'user':{$ne: null}}),但忽略了它。 (我想填充发生在发现呼叫之后,也许就是这个原因)。

有没有什么方法可以在数据库层中过滤它而不必依赖迭代结果,检查null然后过滤掉?

1 个答案:

答案 0 :(得分:0)

GitHub上的

This answer阐明,由于MongoDB的工作原理,populate无法实现。但是,您应该可以使用$lookup来做到这一点。