如何用MongoDB获取每个用户的所有帖子?

cnjp1d6j  于 2022-12-26  发布在  Go
关注(0)|答案(2)|浏览(96)

所以,我开发了一个简单的社交媒体应用程序。
这是我的Post模型

const PostSchema = new mongoose.Schema(
  {
    userId: {
      type: String,
      required: true,
    },
    desc: {
      type: String,
      max: 500,
    },
    img: {
      type: String,
    },
    likes: {
      type: Array,
      default: [],
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Post", PostSchema);

我想检索每个用户的所有帖子。因此,在我的postController中,我尝试编写以下API:

const getAllPosts = async (req,res,next)=>{
    try {
      const posts = await Post.find();
      res.status(200).json(posts);
    } catch (err) {
      next(err);
      
    }
  }

这是中间件

//get all posts
router.get("/allposts",verifyAdmin, getAllPosts);

但它给了我500内部错误。
我是新来的JS,所以谁能帮助我?
编辑:这是服务器端的错误(Postman截图)

ajsxfq5m

ajsxfq5m1#

问题出在find()上,此函数需要参数(第一个:带滤镜的对象)。在这种情况下,可以使用.find({})
正式文件:https://mongoosejs.com/docs/api/model.html#model_Model-find

zysjyyx4

zysjyyx42#

当我将其端点从

//get all posts
router.get("/allposts",verifyAdmin, getAllPosts);

//get all posts
router.get("/",verifyAdmin, getAllPosts);

如果有人能告诉我这背后的原因是什么,我将不胜感激?

相关问题