node.jsdatabasemongodb

Invalid value for schema path `user.type`, got value "undefined"


I am creating a basic social media web application using node.js and mongoDB. I am having trouble with creation of a post. I keep on getting error given above and it keeps on pointing at model post.js line 3:20.

postController.js

const Post = require('../models/post')

const createPost = async (req, res) => {
    try {
        const {media} = req.body;
        const newPost = new Post({
            media: media,
            user: req.userId
        })
        await newPost.save();
        res.status(201).json(newPost);
    } catch (error) {
        console.log(error);
        res.status(500).json({message: "something went wrong"});
    }
}

module.exports = createPost;

post.js

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    media: {
        type: String,
        trim: true,
        required: true
    },
    user: {
        type: mongoose.Schema.Types.objectId,
        ref: "User",
    },
    likes: [
        {
            type: mongoose.Schema.Types.objectId,
            ref: "Like"
        }
    ],
    comment: [
        {
            type: mongoose.Schema.Types.objectId,
            ref: "Comment"
        }
    ]
},{
    timestamps: true,
});

mongoose.export = mongoose.model("Post", postSchema);

post.js(route/api)

const express = require('express');
const createPost = require('../../controllers/postController');
const auth = require('./middleware/auth');
const postRouter = express.Router();

postRouter.get("/", auth, getPost);
postRouter.post("/", auth, createPost);
postRouter.delete("/:postID", auth, deletePost);

module.exports = postRouter;

I am unable to find out what i am doing wrong. please help.


Solution

  • You have a typo, ObjectId must start with a capital letter.
    Change all corresponsing fields definitions to be mongoose.Schema.Types.ObjectId