简体   繁体   中英

Mongoose validation error on POST request

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?

I think it's Mongoose Validation issue, req.body is actually a JSON formatted-data, console.log(req.body.username) returns the username value. To be general, try to use req.body, please make use to fill-out the required fields upon submission.

app.post('/api/posts', function(req, res, next){
var post = new Post(req.body);
post.save(function(err, post){
    if(err){ return next(err) }
    res.json(post)
})
})

Better to handle MongooseError.ValidationError when a user fails to fill-in required fields. Try to review your Mongoose Model.

I got a similar error today, and reading the docs helped me through.

The doc says:

Defining validators on nested objects in mongoose is tricky, because nested objects are not fully fledged paths.

var personSchema = new Schema({
  name: {
    first: String,
    last: String
  }
});

A schema like the above will throw similar error like in your question.

The docs points out the workaround:

var nameSchema = new Schema({
  first: String,
  last: String
});

personSchema = new Schema({
  name: {
    type: nameSchema,
    required: true
  }
});

Source: http://mongoosejs.com/docs/validation.html

in Postman, to test HTTP post actions with raw JSON data, need to select the raw option and also set the header parameters( select header parameter in postman and add in key:value feild which is given below ).

Content-Type: application/json

by default, it comes with Content-Type: text/plain which need to replace with Content-Type: application/json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM