我目前正在创建一个 Node 服务器并使用休息客户端进行测试。我想在 POST 请求中发送 JSON,解析 json 并使用所述有效负载初始化一个新的 mongoose.model 对象,然后将其存储在数据库中。
这似乎需要 body-parser ,它是一个 NPM 包,曾经是 Express 的一部分。获取内部服务器错误。我还确保提供正确的 header (内容类型:application/json)。
我包含的主要代码当前正在工作并保存到数据库,但我使用本地虚拟数据而不是从请求正文实例化的新用户。这是我想用来实例化新用户的 JSON。
{ "_id": 10, "email": "abc@gmail.com", "acct": "12345678", "phone": 9785551212, "cars": [], "address": { "street": "123 Main St.", "city": "boston", "state": "ma", "zip": 2903 }}
在我的阅读中,我发现了许多不同的方法,这些方法应该有效但不起作用:
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(require('connect').bodyParser());
我尝试过的任何方法都不起作用,而且我总是遇到内部服务器错误。预先感谢您的帮助。
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);
});
}
最佳答案
要使用 request.body 中的 JSON 负载实例化新的 Mongoose.model 对象,只需设置每个字段,如下所示。
当尝试执行类似以下操作时,会出现困惑:
var x = new X(request.body).
话虽这么说,我想知道上面的代码是否可行。
请求 header 必须具有 Content-Type:application/json,并且应存在以下正文解析器代码。就我而言,地址包含多个 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
});
关于node.js - Node mongoose 解析 request.body 中的 JSON 负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34521041/