[英]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.
我想在POST请求中发送JSON,解析json并使用所述有效负载初始化一个新的mongoose.model对象,然后将其存储在DB中。
It appears that this requires body-parser , an NPM package that used to be part of express. 看来这需要body-parser ,它是NPM软件包,以前是express的一部分。 Getting internal server errors.
获取内部服务器错误。 I have also made sure to supply the correct headers(Content-type: application/json).
我还确保提供正确的标题(内容类型: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.
这是我要实例化新用户的JSON。
{ "_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. 要使用request.body中的JSON负载实例化一个新的Mongoose.model对象,只需设置每个字段,如下所示。
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. 请求标头必须具有Content-Type:application / json,并且应该存在以下正文分析器代码。 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.
在我的情况下,address包含几个json字段,因此,如果您执行以下操作,似乎正文解析器应该在所有情况下都可以工作。
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.