在Mongo / Mongoose Aggtregation

时间:2018-08-14 12:25:43

标签: node.js mongodb mongoose aggregation-framework

我们已经建立了一些包装器请求功能,以规范我们处理请求的方式。我们设置的功能之一是聚合功能。看起来像这样:

  async aggregate(mongooseModelObject, aggregateObject = {}) {
    try {
      return await mongooseModelObject.aggregate(aggregateObject).exec();
    } catch (err) {
      this.sendError(err);
    }
  }

当我这样使用它时,效果很好:

exports.getCountByBranch = async function (req, res) {
  let docs;
  let request = new EndpointRequestController(req, res);

  try {
    docs = await request.aggregate(staffmember, [{
      $group: {
        _id: "$branch",
        count: {
          $sum: 1
        }
      }
    }]);
  } catch (err) {
    return request.sendError("An error occurred while trying to find existing records.", err);
  }
  request.documentCount = docs.length;
  request.sendResponse(docs);
}

但是,为了使最终用户对用户更友好,我想做的是运行populate以包括分支“名称”,而不只是“ _id”。因此,我认为这就像使用$lookup添加另一个阶段一样简单。如果我只是直接调用猫鼬函数,那将是我要做的。就是说,我尝试了这个:

exports.getCountByBranch = async function (req, res) {
  let docs;
  let request = new EndpointRequestController(req, res);

  try {
    docs = await request.aggregate(staffmember, [{
      $lookup: {
        from: "branches",
        localField: "branch",
        foreignField: "_id",
        as: "branch"
      },
      $group: {
        _id: "$branch",
        count: {
          $sum: 1
        }
      }
    }]);
  } catch (err) {
    return request.sendError("An error occurred while trying to find existing records.", err);
  }
  request.documentCount = docs.length;
  request.sendResponse(docs);
}

但这是错误的:

  

错误:参数必须是集合管道运算符

我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

尝试一下就可以了

phone.value.length

}