【问题标题】:Mongoose find all referenced documentsMongoose 查找所有引用的文档
【发布时间】:2015-07-08 22:45:05
【问题描述】:

mongoose 是否提供了一种从先前查询结果中查找所有引用文档的方法?

例如:

Product
.find(query)
.exec(function(err, results) {
  ...
  Product
  .find({
    '$or': [
      // get all products where _id is in results.associatedProducts[]
    ]
  })
  ...
});

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    我无法找到使用猫鼬本机执行此操作的方法,请参阅下面的工作解决方案。

    Product
      .find(query)
      .exec(function(err, products) {
        ...
        var associatedSoftware = products.reduce(function(memo, current) {
          if(current.features && current.features.associatedSoftware) {
            return memo.concat(current.features.associatedSoftware.map(function(item) {
              return item._id;
            }));
          }
          return memo;
        }, []);
    
        Product.find({
          '$or': [
            ...
            { '_id': { '$in': associatedSoftware } }
            ...
          ]
        })
        .exec(function(err, associated) {
          ...
        });
      });
    

    【讨论】:

      【解决方案2】:

      是的。

      您可以使用query population

      Product
      .find(query)
      .populate('associatedProducts')
      .exec(function(err, results) {
          // ...
      });
      

      这将返回一个格式如下的对象:

      var product = {
          foo: bar,
          associatedProducts: [
              // Here are the associated products
              {
                  // Product Object
              },
              {
                  // Product Object
              },
              {
                  // Product Object
              }
          ]
      };
      

      【讨论】:

      • 我只对第二个查询的结果感兴趣。 Population 将为上面第一个查询中返回的每个文档填充子文档。
      猜你喜欢
      • 2017-05-13
      • 2015-05-10
      • 2016-04-23
      • 2014-08-23
      • 2016-01-19
      • 1970-01-01
      • 2017-02-28
      • 2023-03-20
      • 2019-06-05
      相关资源
      最近更新 更多