So I was trying to hit a POST request and was getting this error
const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator');
const auth = require('../../middleware/auth');
const Post = require('../../models/Post');
const User = require('../../models/User');
// @route POST api/posts
// @desc Create a post
// @access Private
router.post(
'/',
[auth, [check('text', 'Text is required').not().isEmpty()]],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors)
return res.status(400).json({ errors: errors.array() });
}
try {
const user = await User.findById(req.user.id).select('-password');
const newPost = new Post({
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id
});
const post = await newPost.save();
res.json(post);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
}
);module.exports = router;
I was posting the data with POSTMAN
This is my Posts model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
},
],
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: "users",
},
text: {
type: String,
required: true,
},
name: {
type: String,
},
avatar: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
},
],
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("post", PostSchema);