【发布时间】:2019-02-21 11:15:46
【问题描述】:
我希望能够在 Vapor 3 中向 nosql 数据库批量添加记录。
这是我的结构。
struct Country: Content {
let countryName: String
let timezone: String
let defaultPickupLocation: String
}
所以我试图传递一个 JSON 对象数组,但我不确定如何构造路由,也不确定如何访问数组来解码每个对象。
我试过这条路线:
let countryGroup = router.grouped("api/country")
countryGroup.post([Country.self], at:"bulk", use: bulkAddCountries)
使用此功能:
func bulkAddCountries(req: Request, countries:[Country]) throws -> Future<String> {
for country in countries{
return try req.content.decode(Country.self).map(to: String.self) { countries in
//creates a JSON encoder to encode the JSON data
let encoder = JSONEncoder()
let countryData:Data
do{
countryData = try encoder.encode(country) // encode the data
} catch {
return "Error. Data in the wrong format."
}
// code to save data
}
}
}
那么我如何构建路径和函数以访问每个国家/地区?
【问题讨论】: