0

I'm trying to fetch only the users posts, and i'm using this code:

router.get("/:username", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.params.username });
    const posts = await Post.find({ userId: user._id });
    res.status(200).json(posts);
  } catch (err) {
    res.status(500).json(err);
  }
});

I'm using Postman for testing GET localhost:6000/posts/admin and every time I try it, it gives this error

"name": "CastError",
"message": "Cast to ObjectId failed for value \"admin\" (type string) at path \"_id\" for model \"Post\""

This is my posts collection in Monogodb

enter image description here

And this is the users collection in Mongodb

enter image description here

I don't know what i'm missing here, I just want the link posts/:username shows the posts of this username only

sultan.h
  • 331
  • 1
  • 4
  • 16
  • Are you absolutely sure that this code is throwing this error? Is there some middleware or another match that happens before this controller? – windowsill Nov 18 '22 at 06:55
  • yes, I deleted all the codes in my router and kept only this code and it still giving me the same error – sultan.h Nov 18 '22 at 06:59

1 Answers1

0
const user = await User.findOne({ username: req.params.username });

This query finds user but user._id comes as object but in your db userId saved as a string so you should probably save userId as object

const blogSchema = new Schema({
    title: {
        type: String,
        required: true,
    },
    content: {
        type: String,
        required: true,
    },
    userId: { type: mongoose.Types.ObjectId, ref: 'user' }, //Example
});
YHKdaKING
  • 72
  • 4