Можете да използвате slice on query, последвано от populate.
User.findById({ _id: req.params.id })
.slice('blacklistGroup', [10 * (req.query.currentPage - 1), 10])
.populate("blacklistGroup", "username");
Можете също да използвате aggregate с $slice и $lookup.
User.aggregate([
{"$match":{"_id":req.params.id}},
{"$project":{"blacklistGroup":{"$slice":["$blacklistGroup", 10 * (req.query.currentPage - 1), 10]}}},
{"$lookup":{
"from": usercollection,
"localField": "blacklistGroup",
"foreignField": "_id",
"as": "blacklistGroup"
}},
{"$project":{"usernames":"$blacklistGroup.username"}}])
Можете да го подобрите допълнително, като използвате по-нова версия за търсене.
User.aggregate([
{"$match":{"_id":req.params.id}},
{"$lookup":{
"from":usercollection,
"let":{"blacklistGroup":{"$slice":["$blacklistGroup", 10 * (req.query.currentPage - 1), 10]}},
"pipeline":[
{"$match":{"$expr":{"$eq":["$_id","$$blacklistGroup"]}}},
{"$project":{"username":1,"_id":0}}
],
"as":"blacklistGroup"
}}]);
За пълнота добавете целия пример
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var db = mongoose.connection;
mongoose.set('debug', true);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});
const UserSchema = new mongoose.Schema({
blacklistGroup: [{
type: String,
ref: 'Group'
}]
})
const GroupSchema = new mongoose.Schema({
_id: String,
content: String,
username: String
})
const User = mongoose.model('User', UserSchema, 'users');
const Group = mongoose.model('Group', GroupSchema, 'groups');
module.exports = {
User, Group
}
User.findOne().slice("blacklistGroup", 3).populate("blacklistGroup", "username").exec((err, blacklistGroup) => {
console.log("Populated blacklistGroup " + blacklistGroups);
})
Също така добавен Mongo Playground likn например 2
https://mongoplayground.net/p/YP5l5Kz3sp8