3

I have a Mongoose Schema (Appointment) with two ref fields (sender and receiver). Both referencing the same Schema (User). I am trying to populate these two fields using mongoose-paginate plugin.

The Appointment Schema snippet.

var paginate = require('mongoose-paginate');

var AppointmentSchema = new Schema({
  dateCreated: {type: Date, default: Date.now},
  sender: {type: ObjectId, ref: 'User'},
  receiver: {type: ObjectId, ref: 'User'},
  message: String,
  
  .........................
  
AppointmentSchema.plugin(paginate);

var Appointment = mongoose.model('Appointment', AppointmentSchema);
module.exports = Appointment;

The User Schema snippet.

var UserSchema = new Schema({
  username: String,
  name: {
    first: String,
    middle: String,
    last: String
  },
  
  ..................
  
var User = mongoose.model('User', UserSchema);

module.exports = User;

The mongoose paginate query.

Appointment.paginate({}, request.query.page, request.query.limit,
    function(error, pageCount, appointments, itemCount) {
      if (error) {
         return console.log('ERRRRRRRRRR'.red);
      } else {
        console.log(appointments);
        return response.render('message/inbox',
        {
          pageTitle: "Trash",
          messages: appointments,
          pageCount: pageCount,
          itemCount: itemCount,
          currentPage: currentPage
        });
      }
    }, {columns: {}, populate: 'receiver', populate: 'sender', sortBy: {title: -1}});

This works fine but i want to populate both the sender and receiver fields. Please how do i go about that. I tried passing the fields in JSON but didn't work.

xdzc
  • 1,421
  • 1
  • 17
  • 23

2 Answers2

8

I simply passed in an array of fields to populate and it worked like a charm.

Appointment.paginate({}, request.query.page, request.query.limit,
    function(error, pageCount, appointments, itemCount) {
      if (error) {
         return console.log('ERRRRRRRRRR'.red);
      } else {
        console.log(appointments);
        return response.render('message/inbox',
        {
          pageTitle: "Trash",
          messages: appointments,
          pageCount: pageCount,
          itemCount: itemCount,
          currentPage: currentPage
        });
      }
    }, {columns: {}, populate: ['receiver', 'sender'], sortBy: {title: -1}});
bereket gebredingle
  • 12,064
  • 3
  • 36
  • 47
xdzc
  • 1,421
  • 1
  • 17
  • 23
2

For developers using mongoose-paginate-v2, you can pass an array object to in the pagination options to populate multiple references.

Collection.paginate(query,{
   page : 1,
   limit : 10,
   populate : [
     {
       path : 'refName1',
       select : {field : 1}
     },
     {
       path : 'refName2',
       select : {field : 1}
     }
   ]
})