jspears / mers

Mongoose Express Rest Service
MIT License
343 stars 42 forks source link

POST to /rest/model returns validation error with required #5

Closed richardbrammer closed 11 years ago

richardbrammer commented 11 years ago

Having a UserSchema like:

UserSchema = new Schema({
    username:{type:String, required:true, unique:true, index:true}
});

and posting to /rest/user with Content-Type: application/json and stringified body

{"username":"Richard"}

results in a Object {payload: Array[0], status: 0, error: Object}

with e.g.

jspears commented 11 years ago

first guess is it is not deserializing the object correctly. perhaps a header issue, maybe language related?

jspears commented 11 years ago

I wrote a test case and didn't see that as an issue. Any chance you can provide more details or an example?


var express = require('express'),
    rest = require('../index'),
    request = require('./support/http'),
    mongoose = require('mongoose'),
    should = require('should'),
    Schema = mongoose.Schema,
    json = JSON.stringify,
    app = express();

var UserSchema = new Schema({
    username:{type:String, required:true, unique:true, index:true}
});

var User = mongoose.model('User', UserSchema);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use('/rest', rest({ mongoose:mongoose }).rest())
var connection = mongoose.connection;

module.exports.setUp = function (done) {
    connection.on('open', function () {
        connection.db.dropDatabase(function () {
            console.log('dropped database [' + connection.name + ']');
            done();
        });
    })
    mongoose.connect('mongodb://localhost/user_example_rest')
}
module.exports.tearDown = function(done){
    mongoose.disconnect(function(){
       console.log('disconnecting');
        done();
//        process.exit(0);
    });
}
module.exports.testPut = function (test) {
    request(app)
        .post('/rest/User')
        .set('Content-Type', 'application/json')
        .send(json({"username":"Richard"})).expect(200).end(function (err, res) {
            console.log('response', res.body);
            res.body.should.have.property('status', 0);
            var payload = res.body.should.have.property('payload').obj;
            payload.should.have.property('username', 'Richard')
            payload.should.have.property('_id');
            test.done();

        })
};
richardbrammer commented 11 years ago

Thanks for looking into it. I just solved the problem a few minutes ago. The bodyParser has to be called before mers (rest) (or any routes) what seems to be common knowledge in express, as I didn't find any hints about that.

I am now calling mers after the bodyParser and it is working now, thank you very much, Justin for your help.