@aleshaykovlev
html, css, js, node, webpack, sass, react

CastError: Cast to ObjectId failed for value «user» (type string) at path «_id» for model «Post»?

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


Posts model:
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);


Posts controller:
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;


Posts routes:
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;
  • Вопрос задан
  • 635 просмотров
Пригласить эксперта
Ответы на вопрос 2
@KingstonKMS
Смотрите, что приходит в req.params.id, должна быть уникальная хеш строка. Подробнее про ObjectId - https://mongoosejs.com/docs/schematypes.html#objectids
И еще вот
Ответ написан
@aleshaykovlev Автор вопроса
html, css, js, node, webpack, sass, react
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]);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы