'get reference count with mongodb aggreation

I am working on a mern project and I wanna calculate that how many document(Post) are referencing to a specific document (Post). The reference of any document(Post) is stored in a field named ref which contains the Id of the post it referencing. I wanna store this count in a field named replies. Is it possible to do this with the help of aggregation and $project, if not what approch should I use.

my post model is like this

module.exports = mongoose.model('Post', new mongoose.Schema({
    body: String,
    time: Date,
    author: String,
    ref: String, // Reference of another post
    board: String,
    likes: [String]
}))

my current aggregation pipline looks like this

const posts = await Post.aggregate([
    {
        $match: { board },
    },
    { 
        $project: {
            body: 1, author: 1, time: 1, board: 1, ref: 1,
            likes: { $size: "$likes" }, // calculate number of likes
        } 
    },
    {
        $sort: { time: -1 }
    }
])


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source