我如何获取包含包含 userId 的数组的帖子

问题描述 投票:0回答:1

我正在尝试向我的网站添加书签功能,以便用户可以保存他想要保存的帖子,但它无法按预期工作

假设当用户点击网站上的书签按钮时,他的 ID 会存储在 saves 数组中,然后当用户尝试查看已保存的帖子时,包含该用户 ID 的每个帖子都会存储在 saves 数组中数组被调用。

当我尝试从前端获取数据时,出现此错误 “无法读取未定义的属性(读取‘包含’)”

注意:保存被定义为架构中的用户 ID 数组

这是我的controller.js函数:

 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;
javascript mongodb mongoose-schema
1个回答
0
投票

post
不是以数组形式返回吗?

那么也许您想循环遍历每个元素?

类似:

const savedP = post.filter((singlePost) => singlePost.saves.includes(userId));

© www.soinside.com 2019 - 2024. All rights reserved.