首页 > 解决方案 > 使用 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
    }
    }
}

那么我如何构建路线和功能以访问每个国家/地区?

标签: arraysjsonrecordvapor

解决方案


我不确定您打算使用哪个 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
    }
}

推荐阅读