如何根据用户ID搜索论坛帖子?搜索接口代码错误修复及ownerID搜索方法咨询
Hey there! Let's break down how to fix your search endpoint and clarify the ownerID search question.
1. Fixing the "Search User-Created Forums" Endpoint
Your current get function has a key mistake: Forum.findById(userID) looks for a forum post using the forum's own ID, not the ID of the user who created it. Let's fix this based on how you're storing the creator in your create endpoint.
First, Let's Recap Your Creator Storage
In your create function, you're fetching a User document and assigning it directly to newForum.createdBy:
const users = await User.findOne({ userID: user }); // ... newForum.createdBy = users;
This means your Forum documents have the full User object nested in createdBy. While it's more common to store just the User's _id (for better performance and normalization), let's cover both scenarios:
Scenario 1: If you keep storing the full User object in createdBy
To find all forums created by a user with a specific userID, you need to query the nested createdBy.userID field:
exports.get = async (req, res, next) => { const { userID } = req.body; try { // Find all forums where the nested createdBy.userID matches the input const forums = await Forum.find({ "createdBy.userID": userID }); if (forums.length === 0) { return res.status(404).json({ message: "No forums found for this user" }); } res.status(200).json(forums); } catch (error) { error.status = 400; next(error); } };
Scenario 2: Recommended - Store only the User's _id in createdBy
This is the standard MongoDB practice for relationships. First, update your create function to store the User's ID instead of the full object:
exports.create = async (req, res) => { const userIDFromToken = req.token; const user = await User.findOne({ userID: userIDFromToken }); // Add error handling if the user doesn't exist if (!user) { return res.status(404).json({ message: "User not found" }); } const { forumName, forumDescription } = req.body; const errors = []; if (!forumName) { errors.push({ text: "Please Write a Title." }); } if (!forumDescription) { errors.push({ text: "Please Write a Description" }); } if (errors.length > 0) { res.render("forum/", { errors, forumName, forumDescription }); } else { const newForum = new Forum({ forumName, forumDescription, createdBy: user._id // Store only the User's ObjectId }); await newForum.save(); // Optional: Populate the createdBy field to return user data with the forum const populatedForum = await Forum.findById(newForum._id).populate('createdBy', 'userID'); res.status(201).json(populatedForum); } };
Then update your get function to query using the User's _id:
exports.get = async (req, res, next) => { const { userID } = req.body; try { // First find the user to get their ObjectId const user = await User.findOne({ userID: userID }); if (!user) { return res.status(404).json({ message: "User not found" }); } // Find all forums created by this user const forums = await Forum.find({ createdBy: user._id }); if (forums.length === 0) { return res.status(404).json({ message: "No forums found for this user" }); } // Optional: Populate to include user details const populatedForums = await Forum.populate(forums, { path: 'createdBy', select: 'userID' }); res.status(200).json(populatedForums); } catch (error) { error.status = 400; next(error); } };
Quick Note on Request Structure
For search endpoints, it's more RESTful to use query parameters instead of the request body. For example, change your endpoint to GET http://localhost:8080/forum?userID=xxx and fetch the ID with const userID = req.query.userID; instead of req.body.
2. How to Search by ownerID
Assuming ownerID is a field in your Forum model (similar to createdBy), the approach mirrors the fixes above:
- If
ownerIDstores a User's_id: Useawait Forum.find({ ownerID: targetOwnerId }); - If
ownerIDstores a full User object: Useawait Forum.find({ "ownerID.userID": targetOwnerUserId }); - If
ownerIDis a direct custom ID (not linked to the User model): Simply useawait Forum.find({ ownerID: targetOwnerID });
Just make sure your query matches how you're storing the ownerID value in your Forum documents.
内容的提问来源于stack exchange,提问作者Deezer

