使用带有Vapor和Fluent的Mongo DB

时间:2016-10-02 09:39:44

标签: mongodb fluent vapor

我为看起来像这样的用户制作了一个模型:

import Vapor
import Fluent
import Foundation

final class User: Model {

var id: Node?
var username: String
var name : String
var surename : String
var password : String
var credit : String
var isBlocked : String
var isAdmin : String

init(username: String, name: String, surename: String, password: String, credit: String, isBlocked: String, isAdmin: String) {
    self.id = UUID().uuidString.makeNode()
    self.username = username
    self.name = name
    self.surename = surename
    self.password = password
    self.credit = credit
    self.isBlocked = isBlocked
    self.isAdmin = isAdmin
}

init(node: Node, in context: Context) throws {
    id = try node.extract("_id")
    username = try node.extract("username")
    name = try node.extract("name")
    surename = try node.extract("surename")
    password = try node.extract("password")
    credit = try node.extract("credit")
    isBlocked = try node.extract("isBlocked")
    isAdmin = try node.extract("isAdmin")

}

func makeNode(context: Context) throws -> Node {
    return try Node(node: [
        "_id": id,
        "username": username,
        "name": name,
        "surename": surename,
        "password" : password,
        "credit" : credit,
        "isBlocked" : isBlocked,
        "isAdmin" : isAdmin
    ])
}
}

//extension User {
//    /**
//        This will automatically fetch from database, using example here to   load
//        automatically for example. Remove on real models.
//    */
//    public convenience init?(from string: String) throws {
//        self.init(content: string)
//    }
//}

extension User: Preparation {
static func prepare(_ database: Database) throws {
    try database.create("users") { users in
        users.id()
        users.string("username")
        users.string("name")
        users.string("surename")
        users.string("password")
        users.string("credit")
        users.string("isBlocked")
        users.string("isAdmin")
    }
}

static func revert(_ database: Database) throws {
    //
}
}

我尝试用这个创建一个新用户:

    var user = User(username: "Test", name: "Name", surename: "zuname", password: "1234", credit: "0.00", isBlocked: "false", isAdmin: "true")

    try user.save()
    print(user.id) // prints the new id

我可以建造并运行蒸汽。当我进入路线时,应该执行该错误:

  

未捕获错误:EntityError.noDatabase。使用中间件来捕获此错误并提供更好的响应。否则,将在生产环境中返回500错误页面。

任何人都可以帮助我吗?

我在哪里可以找到关于mongo和Vapor的Fluent的完整文档?

非常感谢!

1 个答案:

答案 0 :(得分:9)

当模型不知道要使用哪个数据库时,会发生EntityError.noDatabase

您有两种方法可以解决此问题。

明确设置User类型的数据库。

User.database = myDatabase

或者,传递User类型作为Droplet的准备。

let drop = Droplet(preparations: [User.self])