arrays - 使用 Vapor3 将多条记录插入数据库
问题描述
我希望能够将记录批量添加到 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
}
}
}
那么我如何构建路线和功能以访问每个国家/地区?
解决方案
我不确定您打算使用哪个 NoSQL 数据库,但 MongoKitten 5 和 Meow 2.0 的当前 beta 版本使这非常容易。
请注意,当我们首先推送到稳定的 API 时,我们还没有为这两个库编写文档。以下代码大致是您使用 MongoKitten 5 所需要的:
// Register MongoKitten to Vapor's Services
services.register(Future<MongoKitten.Database>.self) { container in
return try MongoKitten.Database.connect(settings: ConnectionSettings("mongodb://localhost/my-db"), on: container.eventLoop)
}
// Globally, add this so that the above code can register MongoKitten to Vapor's Services
extension Future: Service where T == MongoKitten.Database {}
// An adaptation of your function
func bulkAddCountries(req: Request, countries:[Country]) throws -> Future<Response> {
// Get a handle to MongoDB
let database = req.make(Future<MongoKitten.Database>.self)
// Make a `Document` for each Country
let documents = try countries.map { country in
return try BSONEncoder().encode(country)
}
// Insert the countries to the "countries" MongoDB collection
return database["countries"].insert(documents: documents).map { success in
return // Return a successful response
}
}
推荐阅读
- html - 如何将文本的有效区域限制为其兄弟图像?
- apache-spark - 如何强制 Spark SQL 进入代码生成模式?
- django - django中静态文件的正确设置是什么
- php - 简码旨在输出自定义分类法,而不是输出单词“数组”
- reactjs - 复杂的反应错误:错误:元素类型无效:期望字符串(用于内置组件)或类/函数但得到:对象
- cypress - 通过 CircleCI 执行时如何在 Cypress 中订购并行测试执行
- javascript - 使用 Typescript 强制数组中的类型
- cordova - 如何从 ionic 3 打开 google chrome 浏览器
- node.js - 尝试构建时升级节点版本会引发 node-sass 错误
- javascript - JavaScript、Node.JS:无法读写文本文件(异步、等待问题)