问题
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