I'm trying to do a POST request using express on node.js and mongoose for mongoDB but using Postman to get data gives me this error:
Error
at MongooseError.ValidationError (C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\error\validation.js:22:16)
at model.Document.invalidate (C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\document.js:1162:32)
at C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\document.js:1037:16
at validate (C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\schematype.js:651:7)
at C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\schematype.js:679:9
at Array.forEach (native)
at SchemaString.SchemaType.doValidate (C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\schematype.js:656:19)
at C:\Users\Matteo\Desktop\app1\node_modules\mongoose\lib\document.js:1035:9
at process._tickCallback (node.js:355:11)
I paste here my server.js file
var express = require('express')
var bodyParser = require('body-parser')
var mongoose = require('mongoose');
var app = express()
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost/social', function(){
console.log('mongodb connected')
})
var postSchema = new mongoose.Schema ({
username : { type: String, required: true },
body : { type: String, required: true },
date : { type: Date, required: true, default: Date.now}
})
var Post = mongoose.model('Post', postSchema)
app.get('/api/posts', function(req, res, next){
Post.find(function(err, posts){
if(err) { return next(err) }
res.json(posts)
})
})
app.post('/api/posts', function(req, res, next){
var post = new Post({
username : req.body.username,
body : req.body.body
})
post.save(function(err, post){
if(err){ return next(err) }
res.json(201, post)
})
})
app.listen(3000, function(){
console.log('Server listening on', 3000)
})
Can anyone help me or it is a problem of mongoose?
req.body
an actual object withusername
andbody
? I see that you're missing inclusion ofbodyParser
middleware, as in:app.use(bodyParser.json());
line,. – bardzusnyconsole.log(req.body)
print to the console? – royhowieapp.use(bodyParser.urlencoded({ extended: true }))
– royhowie