Parse Server, MongoDB - get "liked" state of an object Parse Server, MongoDB - get "liked" state of an object database database

Parse Server, MongoDB - get "liked" state of an object


I'd advise agains directly accessing MongoDB unless you absolutely have to; after all, the way collections and relations are built is an implementation detail of Parse and in theory could change in the future, breaking your code.

Even though you want to avoid multiple queries I suggest to do just that (depending on your platform you might even be able to run two Parse queries in parallel):

  1. The first one is the query on Comment for getting all comments you want to display; assuming you have some kind of Post for which comments can be written, the query would find all comments referencing the current post.
  2. The second query again is for on Comment, but this time
    • constrained to the comments retrieved in the first query, e.g.: containedIn("objectID", arrayOfCommentIDs)
    • and constrained to the comments having the current user in their likers relation, e.g.: equalTo("likers", currentUser)


Well a join collection is not really a noSQL way of thinking ;-)I don't know ParseServer, so below is just based on pure MongoDB.

What i would do is, in the Comment document use an array of ObjectId's for each user who likes the comment.

Sample document layout

{     "_id" : ObjectId(""),     "name" : "Comment X",     "liked" : [        ObjectId(""),         ....    ]}

Then use a aggregation to get the data. I asume you have the _id of the comment and you know the _id of the user.

The following aggregation returns the comment with a like count and a boolean which indicates the user liked the comment.

db.Comment.aggregate(    [        {            $match: {            _id : ObjectId("your commentId")            }        },        {            $project: {                _id : 1,                name :1,                number_of_likes : {$size : "$liked"},                user_liked: {                            $gt: [{                                $size: {                                    $filter: {                                        input: "$liked",                                        as: "like",                                        cond: {                                            $eq: ["$$like", ObjectId("your userId")]                                        }                                    }                                }                            }, 0]                        },            }        },    ]);

this returns

{ "_id" : ObjectId(""), "name" : "Comment X", "number_of_likes" : NumberInt(7), "user_liked" : true

}

Hope this is what your after.