Answer the question
In order to leave comments, you need to log in
CastError: Cast to ObjectId failed for value "user" (type string) at path "_id" for model "Post"?
user model:
const {Schema, model, Types} = require("mongoose");
const schema = new Schema({
name: {type: String, required: true},
email: {type: String, required: true, unique: true},
password: {type: String, required: true},
posts: [{type: Types.ObjectId, ref: "Post"}],
avatar: {type: String, required: true, default: "https://cdn.pixabay.com/photo/2013/07/13/12/07/avatar-159236_960_720.png"},
friends: [{type: Types.ObjectId, ref: "User"}],
subscribes: [{type: Types.ObjectId, ref: "User"}]
});
module.exports = model("User", schema);
const {Schema, model, Types} = require("mongoose");
const schema = new Schema({
title: {type: String, required: true},
description: {type: String, required: true},
owner: {type: Types.ObjectId, ref: "User"},
createdAt: {type: Date, required: true, default: Date.now},
coverImage: {type: String, default: "no"},
likes: {type: Number, default: 0, required: true},
comments: [{type: Types.ObjectId, ref: "Comment"}],
views: {type: Number, default: 0}
})
module.exports = model("Post", schema);
const Post = require("../models/Post");
class Postscontroller {
async getUserPosts(req, res) {
try {
const posts = await Post.find({owner: req.params.id});
res.json(posts);
} catch(e) {
console.log(e);
res.status(500).json({message: "Ошибка сервера: " + e.message});
}
}
}
module.exports = Postscontroller;
const router = require("express").Router();
const Postscontroller = require("../controllers/posts.controller");
router.get("/user/:id", authMiddleware, (req, res) => {
new Postscontroller().getUserPosts(req, res);
})
module.exports = router;
Answer the question
In order to leave comments, you need to log in
See what comes in req.params.id, it should be a unique hash string.
More about ObjectId - https://mongoosejs.com/docs/schematypes.html#objectids
React.useEffect(() => {
let isMounted = true;
async function fetchPosts(){
try {
const response = await fetch(`http://localhost:5000/api/posts/user/${user._id}`, {
method: "GET",
headers: {
"Authorization": `Bearer ${currentUser.token}`
}
})
await response.json().then(data => {
if (isMounted) setPosts(data);
})
} catch(e:any) {
alert(e.message);
}
return () => {isMounted = false};
}
user._id && fetchPosts(); // добавил проверку на существование идентификатора
}, [currentUser.token, user._id]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question