0

Creating a friends system in express/handlebars/mongoose. I'm using {{friends.length}} to show the total number of friends a user has, but how would I show the total types of friends. eg.

how many of those friends have status of 0 or 1.

0 = pending 1 = friends

How do I get the count of each through mongo/mongoose?

var UserSchema = new Schema({
    username   : String,
   friends    : [{ id: { type: Schema.Types.ObjectId, ref: 'User'}, status: Number }]
});

app.get('/:username/friends', function(req, res) {
  User
  .findOne({ username: req.params.username }, 'username friends')
  .populate({
    path: 'friends.id',
    model: 'User',
    select: 'username'
  })
  .exec(function(err, user) {
    res.render('friends', user)   
  })
});

    {
        "_id" : ObjectId("590ac6b7663350948be1c085"),
        "username" : "some username", 
        "friends" : [ 
            {
                "id" : ObjectId("590ac6ac663350948be1c083"),
                "status" : 1,
                "_id" : ObjectId("590ace171aa0aeb58f798466")
            }
        ]
    }
totalnoob
  • 2,521
  • 8
  • 35
  • 69

1 Answers1

1

If I right understand you, you have array of all friends so you can use filter for it:

friendsType1 = friends.filter(friend=>friend.satatus===0);
friendsType2 = friends.filter(friend=>friend.satatus===1);
friendsType1.length;//total count friends with status 0
friendsType2.length//total count friends with status 1

Under UserSchema you can declare methods:

//find friends with status 1
UserSchema.statics.findFriends = function (username, clb){
    mongoose.models.User
    .findOne({ username: req.params.username }, 'username friends')
    .populate({
     path: 'friends.id',
     model: 'User',
     select: 'username'
    })
    .exec(function(err, user) {
      if(err) return clb(err);

      var result = user.friends.filter(friend=>friend.satatus===1);
      clb(null, result);        
    })
}

Then you can use it like this:

app.get('/:username/friends', function(req, res) {
  User.findFriends(req.params.username, function(err, users){
    if(err) throw err;
    res.render('friends', users);
  });   
});
Sergaros
  • 821
  • 1
  • 5
  • 14