我有一个用户和帖子文档如下:
user: {
"name": "Test",
interests: [
"Sports",
"Movies",
"Running"
]
}
post: {
"title": "testing",
"author": ObjectId(32432141234321411) // random hash
}
我想查询帖子并获取作者有“运动”、“运行”作为兴趣的所有帖子,这将是一个分页查询。
我怎样才能在 Mongoose 中做到这一点,如果不是,我应该使用什么替代方案?
最佳答案
使用限制和跳过进行分页
var limit = 5;
var page = 0; // 1,2,3,4
return Model.find({
/* Some query */
})
.limit(limit)
.skip(limit * page)
.exec().then((data) => {
console.log(data);
});
试试这个
const findUser = (interests) => {
return User.find({
interests: {
$in: interests
}
}).exec();
};
const findPost = (query, page = 0) => {
const limit = 5;
return Model.find(query)
.limit(limit)
.skip(limit * page)
.exec();
};
var execute = async () => {
const users = await findUser(["Sports", "Movies", ]);
users.forEach(user => {
user.post = await findPost({
"post.author": user._id
});
});
return users;
}
关于node.js - Mongoose 的分页结果,带有引用文档的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49168207/