I can't store data into MongoDB(Atlas) on Postman (Node.js with express)

Viewed 665

It’s my first post.

I’m trying to post a data which is object includes “title”,”body”,”snippet” into backend which I use Mongo DB Atlas.

However when I test it on postman, I can’t store those data into a schema which is prepared in model.

The error message:

 “   title: MongooseError [ValidatorError]: Path `title` is required.
        at new ValidatorError ”

Others(body,snippet) are also null.

app.js:

const express = require('express'),
      mongoose = require('mongoose'),
      cors = require('cors'),
      app = express(),
      blogRoutes = require('./routes/blogRoute');

// connect to mongoDB
const dbURI = '';
mongoose.connect(dbURI,{ useNewUrlParser: true,useUnifiedTopology: true } )
.then(result => {
    // Listen for requests
    app.listen(3000);
})
.catch((err) => console.log(err));

// Middleware & static files
app.use(express.urlencoded({ extended: true }))

// cors
app.use(cors({ origin: true, credentials: true }))

//Blog Router
app.use('/blogs/api',blogRoutes);

//404
app.use((req,res) => {
    res.render('404',{ title:'Not Found' });
})

Model file:

const mongoose = require('mongoose'),
      Schema = mongoose.Schema;

const blogSchema = new Schema({
    title:{
        type:String,
        required:true
    },
    snippet:{
        type:String,
        required:true
    },
    body:{
        type:String,
        required:true
    },
}, { timestamps:true })

// create model
const Blog = mongoose.model('Blog',blogSchema);

module.exports = Blog;

Controller(store):

// Store
const blog_create_post = async (req,res) => {
    const {title,snippet,body} = req.body;
    try {
        const blog = await Blog.create({ title,snippet,body });
        res.status(201).json(blog);
        console.log(blog);
    } catch (error) {
        res.status(400);
    }
}

router: // Store

router.post('/',blogController.blog_create_post)

Even though GET works fine, I’m stuck in this error for a long time on POST method…

I would appreciate if you suggest something.

1 Answers

In your mongoose schema, you have mentioned required for the title as below and while creating a new document mostly it is empty hence the error title: MongooseError [ValidatorError]: Path title is required. at new ValidatorError

title:{
        type:String,
        required:true
    },

Also, your Controller is catering title properly.

It can be the way you are sending data from the postman if you are sending raw and JSON then add below middleware comment

app.use(express.json());
Related