node.js - 检索按创建的包含给定参数的对象数排序的用户列表
问题描述
我用 Javascript 开发 API 并使用 MongoDB 作为我的数据库(mongoose v5.9.26)。
我面临着这个非常艰难的 mongoose 查询创建,我希望得到一些帮助来找出使用 Mongoose 构建它的正确方法。
鉴于下面提供的对象模式,我想检索一个用户列表 ([createdBy]),按用户在参数中接收的类别中创建的对象数量排序。我会在 Get 查询中收到包含类别的正文。
export const ObjectSchema = new Schema({
createdBy: { type: Schema.Types.ObjectId, ref: 'User', required: true},
title: { type: String, required: true },
category: { type: CategorySchema, required: false },
}, { timestamps: true });
我想避免查询包含在参数中接收到的类别的所有对象,并在 javascript 中执行所有排序逻辑。
先感谢您
解决方案
对于那些碰巧遇到这种情况的人,我能够构建我的查询,集成分页。
const group = await this.timenoteModel.aggregate([
{ $match: { 'category.category': { $regex: category.category, $options: 'i'}, 'category.subcategory': {$regex: category.subcategory, $options: 'i'} } },
{ $group: {
_id: '$createdBy',
count: { $sum: 1 },
}},
{ $sort: { count: -1 } },
{ $skip: offset * USER_PAGINATE_LIMIT },
{ $limit: USER_PAGINATE_LIMIT }
]);
const users = await this.userModel.populate(group, {path: '_id'});
推荐阅读
- python - 我不明白为什么我以后不能使用 user_choice 作为它的“未定义”
- python - 过滤数组数组
- node.js - node.js 不和谐机器人使用输入作为机器人输出和反应
- python - 将 DataFrame 插入雪花时,snowflake.connector.errors.ProgrammingError: 001003 (42000)
- javascript - 尝试在我的业务关闭时更改链接的路径
- numpy - 如何在 Python 中将点 (x,y,z) 投影到 (x,y) 上?
- c# - POST 控制器操作方法的 LIST 返回计数 = 0
- python - 如何保存从 Django 模型中的模板获取的对象列表?
- c++ - 如何从 C++ 代码中检索 QML 的 TextField 中的文本?
- apache - 无法使用 Ubuntu/Apache 从 .NET Core Web 应用程序加载静态文件