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
And this is the users collection in Mongodb
I don't know what i'm missing here, I just want the link posts/:username shows the posts of this username only
CodePudding user response:
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
});
CodePudding user response:
Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the matching doc. This is an ObjectId but "foo" is not a valid ObjectId so the cast fails.
This doesn't happen with 41224d776a326fb40f000001 because that string is a valid ObjectId.
One way to resolve this is to add a check prior to your findById call to see if id is a valid ObjectId or not like so:
if (id.match(/^[0-9a-fA-F]{24}$/)) {
// Yes, it's a valid ObjectId, proceed with `findById` call.
}