gpt4 book ai didi

mongodb - 在 Vapor 和 Fluent 中使用 Mongodb

转载 作者:可可西里 更新时间:2023-11-01 09:20:09 24 4
gpt4 key购买 nike

我为用户制作了一个模型,如下所示:

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

我可以构建和运行 Vapor 。当我进入应该执行的路线时,我收到了这个错误:

Uncaught Error: EntityError.noDatabase. Use middleware to catch this error and provide a better response. Otherwise, a 500 error page will be returned in the production environment.

有人能帮帮我吗?

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

非常感谢!

最佳答案

EntityError.noDatabase 在模型不知道要使用哪个数据库时发生。

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

User 类型显式设置数据库。

User.database = myDatabase

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

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

关于mongodb - 在 Vapor 和 Fluent 中使用 Mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com