Search and filter documents on main document fields and populted fields too

Here we are, I show you my case
I’m working with nodejs + express + mongose
I have a Users model which has a role field which is the id of the roles collection

const userSchema = new mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    createdAt: {type: Date},
    updatedAt: {type: Date},
    deletedAt: {type: Date},
    createdBy: {type: mongoose.Schema.Types.ObjectId},
    updatedBy: {type: mongoose.Schema.Types.ObjectId},
    deletedBy: {type: mongoose.Schema.Types.ObjectId},
    name: {
      type: String,
      trim: true,
      required: 'Please enter user name'
    },
    email: {
      type: String,
      trim: true,
      required: 'Please enter user email',
      lowercase: true,
      unique: true,
      match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please fill a valid email address']
    },
    role: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref: 'roles'
    }
  }
);

Here is the Roles model

const roleSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  createdAt: {type: Date},
  updatedAt: {type: Date},
  deletedAt: {type: Date},
  createdBy: {type: mongoose.Schema.Types.ObjectId},
  updatedBy: {type: mongoose.Schema.Types.ObjectId},
  deletedBy: {type: mongoose.Schema.Types.ObjectId},
  name: {
    type: String,
    trim: true,
    required: 'Please enter a valid role name'
  }
});

To view the users including role I used the statement

Users
.find()
.populate("role")

The goal is that by writing “Editor” in the search input only users who have the Editor role will be filtered and displayed.
Any idea?

Ok I found it an elegant solution:
Instead using find().populate(“roel”) i had to use aggregate() with $lookup and $set

.aggregate(
    [
      {
        $lookup: 
          {
            from: "roles",
            localField: "role_id",
            foreignField: "_id",
            as: "role_obj",
            pipeline: [
              {
                $project: {
                  name:1
                }
              }
            ]
          }
      },
      {
          $set: 
          {
            role_name: { $arrayElemAt: [ "$role_obj.name", 0 ] }
          }
      }
   ]
)

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.