0

Every post has comments, and users can 'like' a comment. What Im trying to achieve is when a user is viewing a posts comments they will be able see the ones they've liked and not currently liked (allowing to like and unlike any comment)

Schema for Comments:

// ====================
// Comment Likes Schema
// ====================

var CommentLikes = new Schema({
    userId:String,
    commentId:String
})

// ==============
// Comment Schema
// ==============

var CommentSchema = new Schema({
    postId:String,
    authorId:String,
    authorUsername:String,
    authorComment:String,
    likes:[CommentLikes],
    created: {
        type: Date,
        default: Date.now
    },
});

// Comment Model
var Comment = mongoose.model('Comment', CommentSchema, 'comment');

This seems like the best way to handle Comment Likes by using Embedded Documents.

Currently Im selecting all the post comments like so:

Comment.find({ postId:req.params.postId }).sort({ _id: -1 }).limit(20)
.exec(function (err, comments) {
    if(err) throw err

    // === Assuming Comment Likes Logic Here

    // Return
    return res.send({
        comments:comments,
    })
})

At the moment I'm returning all the likes back, irrespective of the current users Id. If the comment has 50k likes then this surely would be inefficient to send all the likes back, therefore I want to get all the comments but only the likes that have been created by the logged in user (using userId). What would be the most efficient way to do this? My first thought was to just run another find and get them that way? But surely can I not just run a find() on the parent then limit the Embedded Documents?

HireLee
  • 489
  • 1
  • 9
  • 22
  • Possible duplicate of [How to filter array elements](http://stackoverflow.com/questions/12593998/how-to-filter-array-elements) – Jason Cust Mar 11 '16 at 22:12
  • Using $unwind only seems to work when finding one document. I replicated the code in the linked example and modified it with what i have. Still need to get my head around solving this. Thanks for your input thought @JasonCust :) – HireLee Mar 12 '16 at 12:12

0 Answers0