简体   繁体   中英

node mongoose parse JSON payload in request.body

I am currently creating a node server and testing with a rest client. I would like to send JSON in a POST request, parse the json and initialize a new mongoose.model object with said payload, and then store it in the DB.

It appears that this requires body-parser , an NPM package that used to be part of express. Getting internal server errors. I have also made sure to supply the correct headers(Content-type: application/json).

The main code which I included is currently working and saving to the database, but I am using local dummy data instead of a new user instantiated from the request body. This is the JSON that I would like to instantiate a new user with.

{     "_id": 10,     "email": "abc@gmail.com",     "acct": "12345678",     "phone": 9785551212,     "cars": [],     "address": {         "street": "123 Main St.",         "city": "boston",         "state": "ma",         "zip": 2903 }}

In my reading, I found many different ways which should work but do not:

app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());

app.use(bodyParser.json({ type: 'application/*+json' }));

app.use(require('connect').bodyParser());

Nothing that I have tried has worked, and I always get internal server errors. Thanks in advance for the help.

   var express = require('express');
var app = module.exports = express();
var mongoose = require('mongoose');
Schema = mongoose.Schema;
//var bodyParser = require('body-parser');


var userSchema = Schema({
    _id: Number,
    email: String,
    acct: String,
    address: {
        street: String,
        city: String,
        state: String,
        zip: Number
    },
    phone: Number,
    cars: [{type: Schema.Types.Number, ref: "Car" }]
});

var carSchema = mongoose.Schema({
    _id: Number,
    _owner: {type: Number, ref: 'User'},
    make: String,
    model: String,
    year: String,
    color: String,
    plate: String
});


var Car = mongoose.model('Car', carSchema);
var User = mongoose.model('User', userSchema);

var sampleUser = new User({
    "_id": 10,
    "email": "abc@gmail.com",
    "acct": 12345678,
    "name": "John Doe",
    "address": {
        "street": "123 Main St.",
        "city": "Boston",
        "state": "Ma",
        "zip": "02903"
    },
    "phone": "9785551212"
});

var car1 = new Car({
    _id : 51,
    _owner: sampleUser._id,
    make: "saab",
    model: "9000",
    year: "1997",
    color: "navy",
    plate: "777000"
});


app.post = function(request, response) {

    var db = mongoose.connection;
    mongoose.connect(process.env.MongoConnectionString);
    db.on('error', function () {

        response.send(500, {message: 'Failed to connect to mongo'});
    });

    db.once('open', function callback() {
        console.log("Sucessfully Logged into mongo");


        //this is the trouble line. I want to use reqest.body, 
        //or json.parse/json.stringify to   
        //parse my json and initialize a new user.

       //var user = new User(request.body);

        sampleUser.save(function (err) {
            if (err)
                return console.log('insert error');
        });



        //save the car to the db
        car1.save(function (err) {
            if (err)
                return console.log('insert error');
        });
        //push the car into the user.cars array and save
        sampleUser.cars.push(car1);
        sampleUser.save();

        //post response
        response.send(statusCodes.OK, sampleUser.cars);




    });

}    

To instantiate a new Mongoose.model object using a JSON payload in request.body, simply set each field as seen below.

Confusion arrises when anything similar to the following is attempted:

var x = new X(request.body). 

That being said, I would like to know if the above code is possible.

The request header must have Content-Type: application/json, and the following body-parser code should be present. In my case, address contains several json fields, so it appears that body parser should work in all scenarios if you do what I did below.

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json()) 

var user = new users({
            _id: request.body._id,
            email:request.body.email,
            account:request.body.account,
            name:request.body.name,
            address:request.body.address,
            phone:request.body.phone
        });

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