使用Mongoose-paginate插件填充多个Mongoose模型字段

时间:2015-04-04 08:44:12

标签: node.js express mongoose mongoose-populate

我有一个带有两个reffield(发送者和接收者)的Mongoose Schema(约会)。两者都引用相同的Schema(用户)。我正在尝试使用mongoose-paginate插件填充这两个字段。

Appointment Schema片段。



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;




用户架构摘录。



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

module.exports = User;




mongoose paginate查询。



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




这工作正常,但我想填充发件人和收件人字段。请问我该怎么做。我尝试在JSON中传递字段但是没有用。

1 个答案:

答案 0 :(得分:5)

我只是将一系列字段传递给填充,它就像一个魅力。

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