Abhilash Shajan
Abhilash Shajan

Reputation: 650

How to find and populate reference object fields in a mongoose schema

I'm trying to fetch data from below mongoose schema, But I'm not sure how to fetch the role field, which is a type of RoleObject.

import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;

const RoleObject = {
  current_role: {
    type: Schema.Types.ObjectId,
    ref: 'Role',
    autopopulate: true
  },  
  new_role: {
    type: Schema.Types.ObjectId,
    ref: 'Role',
    autopopulate: true
  }
}

const UserRequestSchema = new mongoose.Schema({
  group: {
    type: Schema.Types.ObjectId,
    ref: 'Group',
    autopopulate: true,
    required: true
  },
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    autopopulate: true,
    required: true
  },
  role: {
    type: RoleObject
  },
  status: {
    type: String,
    required: true,
    enum: ['pending', 'approved', 'denied']
  },
  type: {
    type: String,
    required: true,
    enum: ['group-join', 'role-change']
  },
  active: {
    type: Boolean,
    required: true
  }
});

UserRequestSchema.index( { group: 1, user: 1 }, { unique: true } );

export { UserRequestSchema };

Here I want populate the role field from the UserRequestSchema, which is given as RoleObject.

Is it possible through populate the field using find method or do I need to use aggregation ?

Upvotes: 0

Views: 88

Answers (1)

Mandeep
Mandeep

Reputation: 364

Try this

UserRequest.find({active:true}).populate({
  path: 'role.current_role role.new_role',
  model: 'Role',
  select: 'name'
}).exec((error, result) => {
  if (error) {    
    console.log(error, " ERROR")
  }
  console.log(result, "Result")
});

If you face any issue. Please let me know

Upvotes: 1

Related Questions