我有以下用户和报告请求表架构,并使用人口来获取和显示报告的用户列表。
var user = new Schema({
name : {type:String,required:[true,"name is required"]},
});
var report_request = new Schema({
user_id : {type:Schema.Types.ObjectId, ref: 'user' },
reported_by_id : {type:Schema.Types.ObjectId, ref: 'user' },
reason : String,
});
但问题是我在列表中有搜索过滤器,并且可以按名称搜索报告的用户。所以我想做这样的事情: report_request.find({'user.name':/Ruby/i});
id Name Reported By
1 Ruby Mark
2 Johny Ruby
我尝试这样做,但没有成功。那么他们还有其他方法可以做到这一点吗?
提前致谢!!
最佳答案
使用population,您可以针对填充的文档发出“子查询”:
report_request.find()
.populate({
path : 'user_id',
match : { name : /Ruby/i }
})
.exec(...)
但是,据我所知,这将首先从数据库中检索所有 repost_request
文档,然后针对 user
运行查询以查找与 /Ruby/i
匹配的文档。
所以就性能而言,这不是一个好的解决方案。但是,根据您所拥有的架构,我认为这是唯一可以通过单个步骤执行的解决方案。
相反,您首先需要查找与名称匹配的用户,并使用他们的 ID 查找属于他们的报告:
user.find({ name : /Ruby/i }).exec(function(err, users) {
var ids = users.map(function(user) { return user.id });
request_report.find({ user_id : { $in : ids } }).exec(function(err, requests) {
...
});
});
(我不记得 { user_id : { $in : users } }
在 Mongoose 中是否也能正常工作;如果是这样,它会为您节省额外的 users.map()
)
关于node.js - 如何使用node.js中的population从两个表中搜索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37614019/