0

suppose we have a User model that contains an array of other User objects.

let UserSchema = mongoose.Schema({
   followers: [{
        type: mongoose.Schema.ObjectId,
        ref: 'User',
    }]
})

I need a count of this objectIds. the first solution is to get length of followers.

req.user.followers.length

but I think it's not relevant to get all the followers that contains many of objectIds. and in my query i dont need all of this objectIds. I tried to use virtuals but in virtuals I have many unnecessary pieces of stuff.I'm looking for the best and uncosted way for this type of situations.

1 Answer 1

3

because of misunderstanding your question, so I update my answer: you can use $size of mongo aggregate.

db.users.aggregate(
   [
      {
         $project: {
            id: 1,
            total_followers: { $size: "$followers" }
         }
      }
   ]
)

In case of you want to find any document with specific number of length (eg: 0), you can do this :

db.users.find({ followers: { $size: 0 } } )
Sign up to request clarification or add additional context in comments.

4 Comments

if I filter {'followers ' :0} .i cant get count of it?
@babakabadkheir I updated my answer :)! with aggregate, you can filter or do whatever on data there.
dude i need a relevant solution. if I use aggregate in everywhere for getting count its not work when i need to populate information of followers.if i have 100 user i must after aggregate use populate this ids .it means aggregate + 100 populate !!
I guess the only way is get req.user.followers.length, because your schema was designed for that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.