populate with mongoose pagination
Asked Answered
D

3

17

i tried to fetch data using npm mongoose-paginate but populate is not working

here is my UsersSchema.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var usersSchema = new Schema({
    name : String,
    created_at : { type : Date, default : Date.now }
});

module.exports = mongoose.model('users',usersSchema);

here is post schema

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mongoosePaginate = require('mongoose-paginate');

var postsSchema = new Schema({
    user : { type: Schema.Types.ObjectId, ref: 'users' },
    post : String,
    created_at : { type : Date, default : Date.now }
});
postsSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('posts',postsSchema);

here is my query

var options = {
    sort:     { created_at: -1 },
    lean:     true,
    offset:   offset,
    populate : 'users',
    limit:    10
};
postsSchema.paginate({user:user},options,function(err,posts){
    if(err){
        console.log(err)
        return false;
    }
    console.log(posts)
});

user provide objectID not a users data. i.e

[{
   user : objectID(987654ff11aa),
   post : 'post'
}]  
Dogmatize answered 5/1, 2018 at 12:57 Comment(0)
V
27

A populate have following things

Post.find({})
.populate([
    // here array is for our memory. 
    // because may need to populate multiple things
    {
        path: 'user',
        select: 'name',
        model:'User',
        options: {
            sort:{ },
            skip: 5,
            limit : 10
        },
        match:{
            // filter result in case of multiple result in populate
            // may not useful in this case
        }
    }
])
.exec((err, results)=>{
   console.log(err, results)
})
Vanatta answered 5/1, 2018 at 13:17 Comment(0)
N
27

If you want to use mongoose-paginate, You can do the following

var query = {};
var options = {
  sort: { date: -1 },
  populate: 'users',
  lean: true,
  offset: offset, 
  limit: 10
};

Post.paginate({}, options, (err, result) => {
 //....
})
Nachison answered 19/9, 2018 at 19:24 Comment(2)
please what if I want to go a step further and query by the user name e.g users with name (user.name) that has the works eye insideSnoopy
Look at the answer here #43729699Nachison
D
0
//* Here are my option that i will use to paginate
var options = {
    sort : { created_at: -1 } ,
    lean : true ,
    populate : 'category_id' ,
    page : req.query.page  ,
    limit : 10 ,
};

//* Paginate with populate
const subcategories = await subcategoryModel.paginate( {} , options ) ;

//* Send all subcategories with the name of the category
if ( subcategories ) {
    return res.status(200).json(subcategories) ;
}
Darcidarcia answered 18/10, 2023 at 20:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.