0

I have this function:

return db.collection( process.env.SPACECOLLECTION ).aggregate( [
            {
                $lookup: {
                    from: "users",
                    localField: "challengers",
                    foreignField: "_id",
                    as: "members"
                }
            }
        ] ).toArray();

What I get:

{
      _id: 5dfa26f46719311869ac1756,
      tokens: [],
      friends: [Array],
      incomingFriendRequest: [],
      incomingSpaceInvites: [],
      name: 'Account 2',
      email: 'account2@gmail.com',
      password: '$2b$10$VRrdAdFdGAlqN5lZ/J/za.S5gqjCpII8LBhPLNiTmHrFDHvESRRTC',
      spaces: [Array]
    }

What I want:

{
      _id: 5dfa26f46719311869ac1756,
      name: 'Account 2',
      email: 'account2@gmail.com',
    }

My issue is that the "users" collection, contains fields such as password and tokens. This is something that I do not want to receive when doing this lookup functions.

Basically my question is: Is there any way to choose what fields from the document I get, similar to how projection works on for example findOne?

IF NOT, how would I go about this? Delete the field in the backend after I got it from the DB?

Thank you!

Cevin Thomas
  • 387
  • 3
  • 14

1 Answers1

1

Yes, you can use $lookup with a custom pipeline like so:

return db.collection( process.env.SPACECOLLECTION ).aggregate( [
    {
        $lookup: {
            from: "users",
            let: { challengers : "$challengers"},
            pipeline: [
                { $match:
                        { $expr: // i'm assuming challengers is an array.
                                { $in: [ "$_id",  "$$challengers" ] },
                        }
                },
                { $project: { password: 0, email: 0 } }
            ],
            as: "members"
        }
    }
] ).toArray();
Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43