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?