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

网站书签功能异常:获取含用户ID的saves数组帖子报错排查

书签功能bug排查:获取收藏帖时出现"Cannot read properties of undefined (reading 'includes')"错误

我正在给网站加书签功能,用户点击按钮就能把帖子加入收藏(把用户ID存入帖子的saves数组),查看收藏帖时要拉取所有saves数组包含当前用户ID的帖子。但前端调用接口时触发错误:Cannot read properties of undefined (reading 'includes')。

注:Schema里已经把saves定义为用户ID数组。

相关代码

控制器代码

const getSavedPosts = async(req, res) => {
 try {
     const userId = req.user._id;
     const post = await Post.find();
     const savedP = await post.saves.includes(userId);
     if(savedP){
     const userSavedPost = await Post.find({userId: {$in: savedP} })
        
         res.status(200).json(userSavedPost);
         console.log(userSavedPost)
         } else {
             return;
         }

     } catch (err) {
         res.status(500).json({ error: err.message });
     }
 };

PostModel.js代码

import mongoose from "mongoose";
    
const postSchema = mongoose.Schema({
    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    text: {
        type: String,
        maxLength: 500
    },
    img: {
        type: String,
    },
    likes: {
        // array of users id's
        type: [mongoose.Schema.Types.ObjectId],
        ref: "User",
        default: []
    },
    saves: {
        // array of users id's
        type: [mongoose.Schema.Types.ObjectId],
        ref: "User",
        default: []
    },
    replies: [
        {
            userId: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'User',
                required: true
            },
            text: {
                type: String,
                required: true
            },
            userProfilePic: {
                type: String,
            },
            username: {
                type: String
            }
        }
    ]
}, {timestamps: true}
)
    
const Post = mongoose.model('Post', postSchema);
    
export default Post;

错误原因及修复

核心问题

  1. Post.find()返回的是数组,无saves属性:await Post.find()会返回所有帖子的数组集合,不是单个帖子文档,所以post.saves必然是undefined,调用includes方法自然报错。
  2. 查询逻辑完全错误:不需要先查所有帖子再手动过滤,直接用MongoDB的内置查询能力就能精准匹配目标帖子。

修复后的控制器代码

const getSavedPosts = async(req, res) => {
  try {
    const userId = req.user._id;
    // 直接查询saves数组包含当前用户ID的帖子
    const userSavedPosts = await Post.find({ saves: userId });
    res.status(200).json(userSavedPosts);
    console.log(userSavedPosts);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

额外优化建议

如果需要返回帖子关联的发帖人信息,可以在查询后添加populate方法:

const userSavedPosts = await Post.find({ saves: userId }).populate('postedBy');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:43:10