Babak Abadkheir
Babak Abadkheir

Reputation: 2350

get length of array field in mongoose _ Nodejs

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.

Upvotes: 0

Views: 2943

Answers (1)

Kai
Kai

Reputation: 3663

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

Upvotes: 3

Related Questions