Shafayat Mamun
Shafayat Mamun

Reputation: 439

How to get an object field as an array in mongoose?

Hello I have a mongoose schema like the following,

const followingFollowersSchema = mongoose.Schema({
  follower: {
     type: mongoose.Schema.ObjectId,
     ref: 'User'
  },
  following: {
     type: mongoose.Schema.ObjectId,
     ref: 'User'
  },
});

I have created a route when called it filters all the users that the current logged in user is following and shows the following output,

{
  "status": "success",
  "results": 1,
  "data": {
    "following": [
            {
              "_id": "5ef4cd0205070d87156e19da",
              "following": {
                  "_id": "5eeb92d69fceed6d91ad5743",
                  "name": "X Y"
            }
          }
      ]
  }
}

But I want to show the output like this,

{
  "status": "success",
  "results": 1,
  "data": {
      "following": [
          {
              "_id": "5eeb92d69fceed6d91ad5743",
              "name": "X Y"
          }
      ]
  }
}

How can I accomplish this? Any help would be appreciated.

Upvotes: 1

Views: 671

Answers (1)

mickl
mickl

Reputation: 49945

You can use $addFields to replace existing fields and $map to transform an inner array:

let result = Model.aggregate([
    {
        $addFields: {
            "data.following": {
                $map: {
                    input: "$data.following",
                    in: "$$this.following"
                }
            }
        }
    }
])

Mongo Playground

Upvotes: 2

Related Questions