我正在学习节点,我使用Postman来执行带有身体参数的请求。
对于路由器:router.post(' / locations',ctrlLocations.locationsCreate); 这是控制器:
module.exports.locationsCreate = function (req, res) {
Loc.create({
name: req.body.name,
address: req.body.address,
facilities: req.body.facilities.split(","),
coords: [parseFloat(req.body.lng), parseFloat(req.body.lat)],
openingTimes: [{
days: req.body.days1,
opening: req.body.opening1,
closing: req.body.closing1,
closed: req.body.closed1,
},{
days: req.body.days2,
opening: req.body.opening2,
closing: req.body.closing2,
closed: req.body.closed2,
}]
},
function(err, location){
if(err){
sendJSONresponse(res, 400, err);
} else{
sendJSONresponse(res, 201, location);
}
});
};
在这里,您可以看到我的数据库模型的位置':
var mongoose = require('mongoose');
var openingTimeSchema = new mongoose.Schema({
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
});
var reviewSchema = new mongoose.Schema({
author: {type: String, required: true},
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: {type: String, required: true},
createdOn: {type: Date, "default": Date.now}
});
var locationSchema = new mongoose.Schema({
name: {type: String},
address: String,
rating: {type: Number, "default":0, min: 0, max: 5},
facilities: [String],
coords: {type: [Number], index:'2ndsphere'},
openingTimes: [openingTimeSchema],
reviews: [reviewSchema]
});
mongoose.model('Location', locationSchema);
我没有任何问题需要创建一个新的位置'通过使用mongodb控制台,但我在使用Postman时遇到问题:发送的响应改变了一些'字段的顺序。并在'开放时间添加不需要的ID。
此处x-www-form-urlencoded请求为批量修改:
name:Paquito's Bar
address:41 Lower Brook St, Reading RG1 2AQ, UK
rating:4.5
facilities:WiFi, Coffe, Sexy Staff
lng:-0.9722977
lat:51.4494778
days1:Monday -Friday
opening1:8:00am
closing1:5:00pm
closed1:false
days2:Saturday - Sunday
opening2:10:00am
closing2:12:00pm
closed2:false
结果如下:
{
"__v": 0,
"name": "Paquito's Bar",
"address": "41 Lower Brook St, Reading RG1 2AQ, UK",
"_id": "5774ecf8bcdead7c368a7648",
"reviews": [],
"openingTimes": [
{
"days": "Monday -Friday",
"opening": "8:00am",
"closing": "5:00pm",
"closed": false,
"_id": "5774ecf8bcdead7c368a764a"
},
{
"days": "Saturday - Sunday",
"opening": "10:00am",
"closing": "12:00pm",
"closed": false,
"_id": "5774ecf8bcdead7c368a7649"
}
],
"coords": [
-0.9722977,
51.4494778
],
"facilities": [
"WiFi",
" Coffe",
" Sexy Staff"
],
"rating": 0
}
我在这里创建了API的文档,正如您所看到的那样,订购很糟糕,我不想在开放时间使用_id:我宁愿强制创建ID需要通过代码而不是自动创建。
也许有更好的方法来使用Postman ......任何帮助都会有用。
提前致谢!
答案 0 :(得分:0)
“javascript”中的“字段”顺序并不是GARAUNTETEED,你永远不应该依赖它。
关于“ids” - 你说mongoose在openingTimes
中是另一个模式的数组,因此它就像那样表现。
如果opensTimes是嵌套文档,则应将其定义为嵌套文档,例如像
var locationSchema = new mongoose.Schema({
name: {type: String},
address: String,
rating: {type: Number, "default":0, min: 0, max: 5},
facilities: [String],
coords: {type: [Number], index:'2ndsphere'},
openingTimes: [{
days: {type: String, required: true},
opening: String,
closing: String,
closed: {type: Boolean, required: true}
}],
reviews: [reviewSchema]
});