Friends is an array with pictures as a nested array. How do I limit the number of pictures returned in my query?
const foundUser = await User.findOne({ username: username })
.populate('friends', 'first_name last_name pictures')
Edit: Wording and My solution so far:
let foundUser = await User.findOne({ username: username })
.populate('friends', 'first_name last_name pictures')
.lean();
foundUser.friends = foundUser.friends.map(friend => {
return {
...friend,
pictures: friend.pictures.slice(0, limit),
};
});
However, I'm still interested in a solution which handles limiting the nested pictures array within the query call.
CodePudding user response:
const foundUser = await User.findOne({ username: username })
.populate('friends', 'first_name last_name pictures')
.then((res) => {
let response = res;
res.friends.map((friend, index)=>{
response.friends[index].pictures = friend.pictures.slice(0,limit)
})
return response
})
This maybe helpful for you.
If you are going to use pagination also, the slice method can be designed as ;
response.friends[index].pictures= friend.pictures.slice(((page-1)*limit),limit);