Home > Blockchain >  How to get all posts of every user with MongoDB?
How to get all posts of every user with MongoDB?

Time:12-23

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

CodePudding user response:

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

CodePudding user response:

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?

  • Related