S
S
Stanislav2017-11-10 18:42:14
MongoDB
Stanislav, 2017-11-10 18:42:14

How to check a user's likes for a post?

Tell me how to be and what to do?
There are three collections USERS/POSTS/LIKES
USERS

{
 _id: ObjectID('...'),
 name: 'String'
}

POSTS
{
 _id: ObjectID('...'),
 url: 'String',
 createdBy: 'String User Name'
}

LIKES
{
 _id: ObjectID('...'),
 uid: 'String ObjectID POSTS',
 owner: 'String ObjectID USERS'
}

When you add a like to a post from a user, a new document is created in the LIKES collection, in which
uid - the post ID (POSTS._id) is written
owner - the owner of the like USERS._id
There are 20 posts on the main page and each button has a like post button, so here's how you can check Did the user previously like this post or not?
2 versions come to mind, the first one is simple and understandable, collect the necessary POSTS._id and check it in the likes database, but the second one seems more interesting to me, but I don’t understand how to do it:
There is a ready-made query that selects 20 posts and glues them with Posts.createdBy || USERS.name
Posts
        .aggregate([
            {
                $match: {
                    public: true
                }
            },
            { $sort: { createdAt: -1 }},
            { $skip: offset },
            { $limit: 20 },
             {
                $lookup: {
                    from: 'users',
                    localField: 'createdBy', // Posts.createdBy
                    foreignField: 'name', // Users.name
                    as: 'owner'
                }
            }, {
                $project: {
                    id: 1,
                    url: 1,
                    'owner.ava': 1,
                    'owner.name': 1
                }
            },
            { $unwind: '$owner' }

        ]).exec((e, data) => {

            return c(e || ! data.length ? e || page.notFound : null, data)
    
    });

Is it possible to somehow make a third request in the aggregate to the Likes collection and check if the Posts._id and Users._id record (of the current user (req.user._id)) exists and create additional fields in the received documents verifyLike = true/false

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2017-11-10
@ms-dred

Likes must be stored in the post (and can be cached in the browser, so as not to load the server once again).
In total, one simple and quick request gets the post and likes, without any tricky requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question