Add custom field based on a condition and return a new collection in nodeJs

Viewed 265

I am new to nodejs and I am currently stuck with one query. I have collections user and role. Below is the structure of the same.

User:

{"_id":ObjectId("59ba9b1ey4d6h00012345abe")},
"email":"abc@gmail.com",
"name":"Jane",
"roles":[{"$oid":"1234567af6a8e8901ef9c111"}]}

{"_id":ObjectId("60ba9b1ey4d6h00012345abe")},
"email":"pqr@gmail.com",
"name":"Derek",
"roles":[{"$oid":"1111111af6a8e8901ef9c111"}]}

{"_id":ObjectId("60ba9b1ey4d6h00012345abe")},
"email":"xyz@gmail.com",
"name":"John",
"roles":[{"$oid":"1010101af6a8e8901ef9c111"}]}

Role:

{"_id":ObjectId("1234567af6a8e8901ef9c111")},
"name":"Admin"}

{"_id":ObjectId("1111111af6a8e8901ef9c111")},
"name":"User"}

{"_id":ObjectId("1010101af6a8e8901ef9c111")},
"name":"SuperAdmin"}

Now in NodeJs,I want to retrieve all users with role name "Admin" and "SuperAdmin" and add a new field "IsSuperAdmin" with value "Yes" if it is in role Super Admin.

So Output should be:

[{name:"John",IsSuperAdmin:"YES"},
{name:"Jane",IsSuperAdmin:"NO"}]

I tried below to retrieve the users with required role:

const Admin=  await Role.find({$or: [{ name: 'Admin'}, { name: 'SuperAdmin'}]})
const user=await User.find({ roles: {$in: Admin.map(r => r._id)} }).populate('roles').sort('email');

However,I am not sure on how I would proceed with adding this new field,I tried around $aggregate and $addfields, however stuck at the condition check code.

Any help would be of great help,thanks.

1 Answers
  • $lookup to join roles collection
  • $match id name is equal to Admin or SuperAdmin
  • $project to show required fields and create a field IsSuperAdmin check condition if role name is SuperAdmin then return YES otherwise NO
const users = await User.aggregate([
  {
    $lookup: {
      from: "role", // replace your original collection name
      localField: "roles",
      foreignField: "_id",
      as: "roles"
    }
  },
  {
    $match: {
      "roles.name": {
        $in: ["Admin", "SuperAdmin"]
      }
    }
  },
  {
    $project: {
      _id: 0,
      name: 1,
      IsSuperAdmin: {
        $cond: [
          { $eq: ["$roles.name", ["SuperAdmin"]] },
          "YES",
          "NO"
        ]
      }
    }
  }
])

Playground

Related