How to check if a logged-in user has liked a social post?

Hello! I’m working on a system with a social page, and I need advice on the most efficient way to verify if a logged-in user has already liked a post. Here’s my current setup:

import mongoose from 'mongoose';

const postSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    content: {
      type: String,
      required: [true, 'Por favor, insira o conteúdo do post'],
      maxlength: [500, 'Post pode ter no máximo 500 caracteres'],
    },
    tags: {
      type: [String],
      validate: {
        validator: (v: string[]) => v.length <= 10,
        message: 'Post pode ter no máximo 10 tags',
      },
    },
    likes: {
      type: Number,
      default: 0,
    },
    comments: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Comment',
      },
    ],
  },
  {
    timestamps: true,
  },
);

postSchema.index({ user: 1 });
postSchema.index({ tags: 1 });
postSchema.index({ tags: 1, user: 1 });
export default mongoose.models.Post || mongoose.model('Post', postSchema);

Like:



const likeSchema = new mongoose.Schema({
  post: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Post',
    required: false,
  },
  comment: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
    required: false,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
});

likeSchema.index({ post: 1 });
likeSchema.index({ comment: 1 });
likeSchema.index({ user: 1, post: 1 }, { unique: true });
likeSchema.index({ user: 1, comment: 1 }, { unique: true });

export default mongoose.models.Like || mongoose.model('Like', likeSchema);

comment:

const commentSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    post: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Post',
      required: true,
    },
    content: {
      type: String,
      required: [true, 'Por favor, insira o conteúdo do comentário'],
      maxlength: [500, 'Comentário pode ter no máximo 500 caracteres'],
    },
    likes: {
      type: Number,
      default: 0,
    },
  },
  {
    timestamps: true,
  },
);

export default mongoose.models.Comment ||
  mongoose.model('Comment', commentSchema);

What is the best way to query whether the logged-in user in the session has already liked a post?