首页 > 解决方案 > 检索按创建的包含给定参数的对象数排序的用户列表

问题描述

我用 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 中执行所有排序逻辑。

先感谢您

标签: node.jsmongodbmongoosenestjs

解决方案


对于那些碰巧遇到这种情况的人,我能够构建我的查询,集成分页。

     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'});

推荐阅读