【问题标题】:Querying after populate with RegExp in Mongoose在 Mongoose 中使用 RegExp 填充后进行查询
【发布时间】:2013-08-13 19:49:08
【问题描述】:
我需要根据应用于从 mapReduce 填充的模型的正则表达式来获取文档,但我无法完成:
Article.authors(function(err, model){
model.find({ '_id.surname': /^A/ })
.populate({ path: '_id', model: 'Author' })
.exec(function(err, authors){
...
});
});
你能帮帮我吗?以上没有显示任何内容...
【问题讨论】:
标签:
javascript
regex
mongodb
mongoose
【解决方案1】:
类似这样的:
model.find( { '_id.surname': new RegExp('^A') } )
.populate({ path: '_id', model: 'Author' })
.exec(function(err, authors){
...
});
这里的主要部分是 /^A/ 是 MongoDB shell 特定的语法,在 JavaScript 中您必须使用 new RegExp('^A')。
【解决方案2】:
您确定要密钥 _id.surname。您可能实际上不是在寻找姓氏字段吗?所以应该是
Article.authors(function(err, model){
model.find({ 'surname': /^A/ })
.populate({ path: '_id', model: 'Author' })
.exec(function(err, authors){
...
});
});