【发布时间】:2014-07-11 12:20:40
【问题描述】:
我正在使用 express、body-parser 和 moongose 使用 Node.js 构建一个 RESTful Web 服务。我在 POST 请求的正文中获取 json 数据,该函数如下所示:
router.route('/match')
// create a match (accessed at POST http://localhost:3000/api/match)
.post(function(req, res) {
if (req._body == true && req.is('application/json') == 'application/json' ) {
var match = new Match(); // create a new instance of the match model
match.name = req.body.name; // set the match name and so on...
match.host = req.body.host;
match.clients = req.body.clients;
match.status = req.body.status;
// save the match and check for errors
match.save(function(err) {
if (err) {
//res.send(err);
res.json({ status: 'ERROR' });
} else {
res.json({ status: 'OK', Match_ID: match._id });
}
});
} else {
res.json({ status: 'ERROR', msg: 'not application/json type'});
}
});
我用于在数据库中存储匹配项的模型如下所示:
// app/models/match.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MatchSchema = new Schema({
name: String,
host: String,
clients: { type: [String]},
date: { type: Date, default: Date.now },
status: { type: String, default: 'started' }
});
module.exports = mongoose.model('Match', MatchSchema);
但是如何验证 POST 请求正文中的 json 数据是否具有我想要的键/值字段?为了澄清起见,我不想在不完整的数据库中插入数据。如果我测试跳过 json 数据中的键/值对,我会在数据库中得到一个缺失的字段,当我尝试在我的代码中读取 req.body.MISSING_FIELD 参数时,我会得到未定义。模型中除日期外的所有字段都是必需的。
我正在使用这样的 json 字符串在数据库中添加匹配项
{"name": "SOCCER", "host": "HOST_ID1", "clients": ["CLIENT_ID1", "CLIENT_ID2"], "status": "started"}
【问题讨论】:
-
你为什么不把它们变成必需的?
name: {type: String, required: true}. -
谢谢 Ben,适合大多数部分,但我仍然可以输入一个空数组(客户端)
-
对不起,我的错。现在它起作用了。我有客户:{ type: [{type: String, required: true}]} 但客户:{ type: [{type: String, required: true}], required: true} 解决了我的问题。谢谢!
-
任何人都知道如何捕获格式错误的 json 数据并返回错误消息,如果我发送格式错误的 json 数据,我会收到“SyntaxError: Unexpected token”
-
在 try/catch 块中执行。
标签: json node.js express mongoose