Je zou slice op query kunnen gebruiken, gevolgd door populate.
User.findById({ _id: req.params.id })
.slice('blacklistGroup', [10 * (req.query.currentPage - 1), 10])
.populate("blacklistGroup", "username");
U kunt ook aggregatie gebruiken met $slice en $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"}}])
Je zou het verder kunnen verbeteren met een nieuwere lookup-versie.
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"
}}]);
Voor de volledigheid het hele voorbeeld toegevoegd
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);
})
Ook toegevoegd Mongo Playground likn bijvoorbeeld 2
https://mongoplayground.net/p/YP5l5Kz3sp8