Node.js开发中通过UserId查找用户点赞帖子及验证点赞状态的实现方案
Hey there! Let's work through your two queries step by step—since your likes field is an array of objects (not just raw user IDs), your initial approach can't match the data correctly. Here's how to fix both requirements:
1. Find all posts liked by a specific UserId
To fetch every post the user has liked, you need to target the user field inside the likes array objects. MongoDB supports dot notation to reach into nested array elements, which is perfect here:
// Fetch all posts liked by the given userId const likedPosts = await Audio.find({ "likes.user": userId });
This query looks for any Audio document where at least one element in the likes array has a user property matching your userId. It’s efficient and directly addresses your first need.
2. Check if a UserId exists in a post's like records
If you just need to verify whether a specific user liked a specific post, you’ve got a couple of efficient options:
Option 1: Use exists() for a quick boolean check
This is the simplest way to get a yes/no answer without fetching the full post:
// Check if userId liked the post with postId const hasLiked = await Audio.exists({ _id: postId, "likes.user": userId }); // hasLiked will be true if the user liked the post, false otherwise
Option 2: Use findOne() if you need post data too
If you might need to access the post’s details afterward, use findOne() with a projection to only fetch the fields you need (keeping the query lightweight):
const likedPost = await Audio.findOne( { _id: postId, "likes.user": userId }, { title: 1, _id: 0 } // Only fetch the title example—adjust fields as needed ); const hasLiked = !!likedPost; // Convert the result to a boolean
Why your original query failed
Your initial code const audio = await Audio.find({likes: userId}) tried to match the entire likes array element to a string userId, but each element in likes is an object like { user: "616c09216e4b2ff62f550c39" }. MongoDB can’t match a string to an object, so you need dot notation to target the nested user field instead.
内容的提问来源于stack exchange,提问作者Tutn

