How to get values from aggregation cursor which is not an array Nodejs Mongodb

1.2k views Asked by At

I have an aggregation like this :

this.collection.aggregate([
      {
        "$match": {
          _id: id
        }
      },
      {
        "$addFields": {
          "self": "$$ROOT"
        }
      },
      {
        "$graphLookup": {
          "from": "posts",
          "startWith": "$_id",
          "connectFromField": "_id",
          "connectToField": "postId",
          "as": "postLookup"
        }
      },
      {
        "$addFields": {
          "postLookup": {
            "$concatArrays": [
              "$postLookup",
              [
                "$self"
              ]
            ]
          }
        }
      },
      {
        "$lookup": {
          "from": "comments",
          "localField": "postLookup._id",
          "foreignField": "postId",
          "as": "commentsLookup"
        }
      },
      {
        "$project": {
          children: {
            posts: {
              "$map": {
                "input": "$postLookup",
                "as": "c",
                "in": "$$c._id"
              }
            },
            comments: {
              "$map": {
                "input": "$commentsLookup",
                "as": "t",
                "in": "$$t._id"
              }
            }
          }
        }
      }
    ]);

So the expected result is supposed to be like this:

{
   children: {
        posts: {
            Array
          },
        comments: {
            Array
          }
}
}

The problem is that the aggregation function returns a cursor which can not be converted to an array because it's not a list of documents, it's an object in which you can find inside it the arrays. I couldn't get these two arrays from the cursor itself.. Can someone guide me on what i'm missing here. Thanks

0

There are 0 answers