A
A
Alexey Yakovlev2022-01-09 13:10:07
Node.js
Alexey Yakovlev, 2022-01-09 13:10:07

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


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


Post 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;


Post 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;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2022-01-09
@KingstonKMS

See what comes in req.params.id, it should be a unique hash string. More about ObjectId - https://mongoosejs.com/docs/schematypes.html#objectids

A
Alexey Yakovlev, 2022-01-09
@aleshaykovlev

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 question

Ask a Question

731 491 924 answers to any question