【问题标题】:How to search data from two tables using population in node.js?如何使用 node.js 中的人口从两个表中搜索数据?
【发布时间】:2016-06-03 20:49:38
【问题描述】:

我有以下 UserReport Request 表的架构,并使用人口来获取和显示报告的用户列表。

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

我试图这样做,但它不起作用。那么他们还有其他方法吗?

提前致谢!!

【问题讨论】:

    标签: node.js mongoose-populate


    【解决方案1】:

    使用填充,您可以针对填充的文档发出“子查询”:

    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()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多