我为用户制作了一个模型,如下所示:
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
我可以构建和运行 Steam 。当我进入应该执行的路线时,我收到此错误:
有谁能够帮我?
我在哪里可以找到 Fluent with mongo 和 Vapor 的完整文档?
非常感谢!
最佳答案
当模型不知道要使用哪个数据库时,就会发生 EntityError.noDatabase
。
您有两种方法可以解决此问题。
为 User
类型显式设置数据库。
User.database = myDatabase
或者,传递
User
类型作为 Droplet 的准备。let drop = Droplet(preparations: [User.self])
关于mongodb - 将 Mongodb 与 Vapor 和 Fluent 结合使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39815701/