skip to Main Content

So. I have built a simple social media app.

Here is my Post model

    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);

I want to retrieve every posts of every user that exists.
So, in my postController, I tried to write the following API:

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

Here is the middleware

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

But it gives me 500 internal error.

I am new to JS, so can anyone help me?

EDIT: This is the error at server side (Postman screenshot)
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Somehow it responded to me with 200 server status when I changed its endpoint from

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

    to

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

    Would be thankful if anyone can tell me what can be the reason behind this?


  2. the problem is the find(), this function has required params (first: an object with filter). In this case, you can use .find({}).

    The official documentation: https://mongoosejs.com/docs/api/model.html#model_Model-find

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search