Can anyone please tell me why the given below code(PART-1) works fine whereas gives error that posts.skip is not a function
? in PART-2
I am wondering that why in PART-1 code it returned Query instance whereas I am getting an array of posts.
PART-1
const query = MyModel.find(); // `query` is an instance of `Query`
query.setOptions({ lean : true });
query.collection(MyModel.collection);
query.where('age').gte(21).exec(callback);
PART-2
const posts = await PostModel.find({});
posts.skip((page - 1) * 10).limit(10);
Basically I am trying to refactor this code so that I don't have to each time use pagination
logic and achieve that by writing a pagination util function where the function will have first params a Query instance of mongoose
getAllPost: async (req, res, next) => {
const pagination = req.query.pagination ? parseInt(req.query.pagination) : 10
const currentPage = req.query.page ? parseInt(req.query.page) : 1
try {
const posts = await PostModel.find({}).lean()
.skip((currentPage - 1) * pagination)
.limit(pagination)
.populate('userId', ['name.firstName', 'name.lastName', 'email', 'isAdmin'])
.sort({ updatedAt: -1 })
.exec()
if (!posts.length) {
return res.status(HttpStatus.NOT_FOUND).json({ message: 'No posts found' })
}
return res.status(HttpStatus.OK).json({ posts: posts })
} catch (error) {
HANDLER.handleError(res, error)
}
},
Util function like: (For example)
module.exports = {
paginate: async (req, query, next) => {
const options= {
pagination: req.query.pagination ? parseInt(req.query.pagination) : 10,
currentPage: req.query.page ? parseInt(req.query.page) : 1
}
query.skip((currentPage-1)*pagination).limit(pagination)
query.exec((err, result)=>{ return result; })
}
}
Aucun commentaire:
Enregistrer un commentaire