0

I would like to use the aggregate in mongoose to get documents that match the ids in the array. The array contains mongoose object ids. It is returning an empty array. Here is my code:

let isSelectedTrips = ["******", "*****"]// this actually contains trip ids.

 const me = await Trips.aggregate([
        {
          $match: { isPublished: true, _id: { $in: isSelectedTrips } },
        },
        {
          $facet: {
            getTrips: [{ $skip: skip }, { $limit: Number(searchlimit) }],
            totalDocumentSize: [{ $count: "count" }],
          },
        },
      ]);
      trips = me[0].getTrips;
      totalDocumentSize = me[0].totalDocumentSize[0]?.count || 0;

When I rewrote the conde using find method and used the same $in method, it worked. That means that I may not be doing it properly with the aggregate method. I need to use the aggregate method to also get the total document size before applying limit. I am doing this in Node.js. Here is the version that worked:

  const me = await Trips.find({ _id: { $in: isSelectedTrips }, isPublished: true, });
      trips = me;
      totalDocumentSize = 3;

How do I get the aggregate method to use array of ids to find matching documents?

1 Answer 1

0

You may want to wrap the isSelectedTrips in a mongoose ObjectId instance

let isSelectedTrips = ["******", "*****"]// this actually contains trip ids.

const objectIds = isSelectedTrips.map(id => mongoose.Types.ObjectId(id));

 const me = await Trips.aggregate([
        {
          $match: { isPublished: true, _id: { $in: objectIds } },
        },
        {
          $facet: {
            getTrips: [{ $skip: skip }, { $limit: Number(searchlimit) }],
            totalDocumentSize: [{ $count: "count" }],
          },
        },
      ]);
      trips = me[0].getTrips;
      totalDocumentSize = me[0].totalDocumentSize[0]?.count || 0;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.