Muirik
Muirik

Reputation: 6289

Using a $lookup with $group in Mongo/Mongoose Aggtregation

We have set up some wrapper request functions to normalize how we're handling requests. One of the functions we've set up is an aggregate function. It looks like this:

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

This works fine when I use it like this:

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);
}

But what I'd like to do, to make this more user-friendly for the end-user, is run a populate to include the branch "name", rather than just the "_id". So I would assume that's as simple as adding another stage using a $lookup. That's what I would do if I was just calling the mongoose function directly. So that said, I tried this:

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);
}

But this errors out with this:

Error: Arguments must be aggregate pipeline operators

What am I missing here?

Upvotes: 0

Views: 44

Answers (1)

Senthur Deva
Senthur Deva

Reputation: 787

Try this it's working fine

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

}

Upvotes: 1

Related Questions