You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express+Mongoose用户授权获取专属分类的异常问题排查

Fix: Show Only User-Specific Categories in Express + Mongoose

Hey there! Let's sort out this issue where every user sees all categories instead of just their own. The core problem right now is your Category.find() call isn't filtering results to the logged-in user—here's how to fix it step by step:

First, you need to make sure your Category schema includes a reference to the user who created it. This way, you can later query for categories belonging to a specific user ID.

Update your Category model:

const mongoose = require('mongoose');

const categorySchema = new mongoose.Schema({
  name: String,
  // Add any other fields your categories need here
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User' // Make sure this matches your User model name
  }
});

module.exports = mongoose.model('Category', categorySchema);

Don't forget: When creating new categories, you need to associate them with the current logged-in user. For example, in your POST route for creating categories:

app.post("/category", function(req, res) {
  const newCategory = new Category({
    name: req.body.categoryName,
    user: req.user._id // Attach the logged-in user's ID
  });

  newCategory.save(err => {
    if (err) {
      console.error(err);
      res.redirect("/panel-admin");
    } else {
      res.redirect("/category");
    }
  });
});

2. Filter Categories by Logged-In User in Your GET Route

Now update your /category route to only fetch categories where the user field matches the current user's ID. Also, add a check to make sure the user is actually logged in first:

app.get("/category", function(req, res) {
  // First, verify the user is authenticated
  if (!req.user) {
    return res.redirect("/login"); // Redirect to login if not logged in
  }

  // Query only categories belonging to the current user
  Category.find({ user: req.user._id }, function(err, foundCategories) {
    if (err) {
      console.error(err);
      res.redirect("/panel-admin");
    } else {
      // Pass the filtered categories to your view
      res.render("categories", { categories: foundCategories });
    }
  });
});

3. Protect the Route with Authentication Middleware

To make sure unauthenticated users can't access this route at all, add an authentication middleware. If you're using Passport.js (a common choice for Express auth), you can use its built-in middleware, or create your own:

// Custom authentication middleware
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next(); // User is logged in, proceed to the route
  }
  res.redirect("/login"); // User not logged in, redirect to login page
}

// Update your route to use the middleware
app.get("/category", ensureAuthenticated, function(req, res) {
  // Your filtered category query here (same as step 2)
});

That's it! With these changes, each user will only see the categories they've created when they log in.

内容的提问来源于stack exchange,提问作者cmt123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:43:59