Du kan bruge udsnit på forespørgsel efterfulgt af udfyld.
User.findById({ _id: req.params.id })
.slice('blacklistGroup', [10 * (req.query.currentPage - 1), 10])
.populate("blacklistGroup", "username");
Du kan også bruge aggregat med $slice og $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"}}])
Du kan forbedre den yderligere ved at bruge en nyere opslagsversion.
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"
}}]);
For fuldstændighedens skyld tilføjet hele eksemplet
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);
})
Også tilføjet Mongo Playground likn for eksempel 2
https://mongoplayground.net/p/YP5l5Kz3sp8