Populate Multiple Mongoose Model Fields using Mongoose-paginate plugin

僤鯓⒐⒋嵵緔 提交于 2019-12-24 01:47:29

问题


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.


回答1:


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}});


来源:https://stackoverflow.com/questions/29444429/populate-multiple-mongoose-model-fields-using-mongoose-paginate-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!