0

Model is

const mongoose = require('mongoose')
const Schema = mongoose.Schema

var UserActivitySchema = new Schema({
    author: {type: mongoose.Schema.Types.ObjectId, required: true, unique: true, ref: 'user'},
    readHistory: [{articleid: {type: mongoose.Schema.Types.ObjectId, ref: 'article'}, date_read: {type: Date, default: Date.now()}}],
    watchHistory: [{videoid: {type: mongoose.Schema.Types.ObjectId, ref: 'video'}, date_watch: {type: Date, default: Date.now()}}],
    searchHistory: [{query: String, date:{type: Date, default: new Date()}}]
})

module.exports = mongoose.model('useractivity',UserActivitySchema, 'useractivities')

Here i want to fetch readHistory for which i have used query

   if (req.query.page) var page = parseInt(req.query.page);
else var page = 1;
UserActivity.findOne({author: req.client.userId}).select('readHistory')
.populate({path: 'readHistory.articleid', select: 'title description views thumbnailURI', options: { skip: (page-1)*10, limit: 10}, populate: {path: 'author', select: 'displayName -_id'}})
.exec().then(activity=>{
    if (!activity || activity.readHistory.length <= 0)
        res.json({success: false, message: 'You have not read any article yet.'})
    else {
        res.json({success: true, readHistory: activity.readHistory})
    }
}).catch(err=>{
    res.json({success: false, message: err.message})
})

but it returns all the document in the array. How fix this?

3
  • 2
    It's not the populate() that needs the "limit" here, but the "array". You instead $slice to project a "page" of items findOne({author: req.client.userId}).select({ 'readHistory': { '$slice': [ (page-1)*10, 10 ] }).populate(...) with everything except the options since the $slice is already there. The alternate case is about actually "limiting joins", which is a little more involved and not actually what populate() does, since it's not a "join" but another query retrieving data. Commented Nov 19, 2018 at 20:16
  • Missed a closing } in the select() of that example, but you should get the idea. Note also that the terms "skip" and "limit" are even used in the $slice documentation, since this was the original purpose of the operator way back in the original MongoDB design. Commented Nov 19, 2018 at 20:29
  • 1
    This must be one answer instead a comment. Commented May 20, 2023 at 16:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.