Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

req.body is undefined – only default mongodb id is getting pushed

I have been trying to use post request to insert data to the mongodb using mongoose, however I see that req.body is being shown as undefined. document is getting inserted in database, however only default object id is getting inserted.

This is how I send request to Postman

{
name:"wewe",
price:43}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//Post.js

const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/tutorialkart");

const productSchema = mongoose.Schema({
    name: String,
    price: Number
});
module.exports = mongoose.model('Groduct', productSchema);

//app.js

var express = require('express')
var bodyParser = require('body-parser')
var Post = require('./Post')

var app = express()
app.use(bodyParser.json())



app.post('/api/posts', function (req, res, next) {
    var post = new Post({
        name: req.body.name,
        price: req.body.price
    })
    console.log("Log "+post.name );
    post.save(function (err, post) {
        if (err) { return next(err) }
        res.json(201, post)
    })
})

app.listen(3000, function () {
    console.log('Server listening on', 3000)
})

MongoDB

>Solution :

There are two issues with your request in Postman (you removed the screenshot which showed these issues):

  • it’s not formatted as proper JSON, but as a Javascript object
  • you’re sending it as text/plain, not application/json
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading