MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Help with Aggregate pipeline in Mongoose

I want to send number of posts for each user in this controller response , sorted in descending order
maybe by applying aggregate pipeline on “Post” model and Populating “User” model with that no. posts is the most optimized way but i don’t know how to do it so, please help

const User = require('../../models/user.model'); 
const Friends = require('../friendsModel');
const Util = require('../../../SharedTools/Util');

/**
 * Returns suggesstions for newly registered users.
 * 
 * @param {object} req 
 * @param {object} req.query
 * @param {string} req.query.id
 * @param {number} req.query.page
 * @param {Express.Response} res 
 */
module.exports = function getSuggestionsForMe(req, res) {

    let USER_ID = req.headers['x-user-id'] || req.query.id;
    let PAGE_NO = req.query.page;

    if (Util.IsNullOrUndefined(USER_ID) || Util.IsNullOrUndefined(PAGE_NO)) {

        res.status(400).json(
            {
                success: false,
                message: "Not enough data."
            }
        );

    } else {

        USER_ID = String(USER_ID);
        PAGE_NO = Number.parseInt(PAGE_NO);

        Friends.aggregate(
            [
                {
                    $match: {
                        "from": USER_ID
                    }
                },
                {
                    $group: {
                        _id: "$from",
                        follows: {
                            $push: "$to"
                        }
                    }
                }
            ]
        )
            .then(result => {

                if (result.length !== 0) {

                    User.paginate(
                        { _id: { $nin: result[0].follows } }, 
                        {
                            select: '_id name profilePic category gender place',
                            lean: true,
                            page: PAGE_NO,
                            limit: 30
                        },
                        (err, users) => {

                            if (!err) {

                                let response = {
                                    success: true,
                                    data: users.docs,
                                    numPages: users.pages,
                                    message: "Everything OK"
                                };
                                res.json(response);

                            } else {
                                res.status(500).json({
                                    success: false,
                                    message: "Internal Server Error."
                                });
                            }

                        }
                    );

                } else {

                    User.paginate(
                        { _id: { $ne: USER_ID } },
                        {
                            select: '_id name profilePic place category gender',
                            lean: true,
                            page: PAGE_NO,
                            limit: 30
                        },
                        (err, users) => {

                            if (!err) {

                                let response = {
                                    success: true,
                                    data: users.docs,
                                    numPages: users.pages,
                                    message: "Everything OK"
                                };
                                res.json(response);

                            } else {
                                res.status(500).json({
                                    success: false,
                                    message: "Internal Server Error."
                                });
                            }

                        }
                    );

                }

            })
            .catch(err => {
                res.status(500).json({
                    success: false,
                    message: "Internal Server Error."
                });
            });

    }

}

This is my Friends model (friendSchema):

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const friendsSchema = new Schema({ 

    from:{
        type: Schema.Types.ObjectId,
        required: true,
        ref:'User'
    },
    to:{
        type: Schema.Types.ObjectId,
        required: true,
        ref:'User'
    }

},{
    timestamps: true
});

friendsSchema.index({from:1, to:1}, {unique : true});

module.exports = mongoose.model('Friends', friendsSchema, 'friends');

This is my User model (Userschema):

const Schema = mongoose.Schema;

const userSchema = new Schema({

    name: { type: Schema.Types.String, required: true },
    email: { type: Schema.Types.String, required: true, unique: true },
    password: { type: Schema.Types.String, required: true },
    category: { type: Schema.Types.Number, required: true },

    gender: { type: Schema.Types.String, default: "" },
    dob: { type: Schema.Types.String, default: "" },
    username:{type:Schema.Types.String, unique:true},
    about: { type: Schema.Types.String, default: "" },
    sport: { type: Schema.Types.String, default: "" },
    bankAccountNo: { type: Schema.Types.String, default: "" },
    ifsc: { type: Schema.Types.String, default: "" },

    referralCode : { type: Schema.Types.String, unique: true },
    points: { type: Schema.Types.Number, default: 0 },  

    phone: { type: Schema.Types.String, default: "" },
    profilePic: { type: Schema.Types.String, default: "" },
    coverPic: { type: Schema.Types.String, default: "" },
    place: { type: Schema.Types.String, default: "" },
    active: { type: Schema.Types.Boolean, default: false },
    token: { type: Schema.Types.String, default: "" }

}, {
    timestamps: true
});
userSchema.plugin(mongoosePaginate);

module.exports = mongoose.model('User', userSchema);

This is my Post model (PostScema):

var mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate');  
var Schema = mongoose.Schema;

var postSchema = new Schema({

    postedBy:{
        type:Schema.Types.ObjectId,
        ref:'User',
        required:true
    },
    text:{
        type:String,
        default:""
    },
    imageUrl:{
        type:String,
        default:""
    },
    mediaType:{
        type:String,
        default:""
    },
    likeCount:{
        type:Number,
        default:0
    },
    likes:{
        type:[Schema.Types.ObjectId],
        ref:'User',
        default:[]
    },
    commentCount:{
        type:Number,
        default:0
    },
    tags:{
        type:[Schema.Types.String],
        default:[]
    }

},{
    timestamps:true
});
postSchema.plugin(mongoosePaginate);


module.exports = mongoose.model('Post', postSchema);

@Anil_Yadav could you please re-format your question, it is difficult to trace your code. and also please state your question clearly.

This what my post collections looks like in compass, i want to send number of posts for each user in my response

i want to send number of posts for each user in my getsuggestionforme function in a optimized way