如何使用 Mongokitten 在蒸汽中创建模型 [英] How to create a model in vapor using Mongokitten
问题描述
这是模型,我必须使用 mongokitten 将其更改为 mongo 模型.
这是我的朋友 Model,我已经实现了.这但不能为这种模式制作一个嵌套的 json 结构.
This is my friend Model and I have implemented. This but not able to make a nested json like structure for this mode.
import Foundation
import Vapor
import Fluent
struct Friend: Model {
var exists: Bool = false
var id: Node?
var name: String
var age: Int
var email: String
var residence: FriendAddress
init(name: String, age: Int, email: String ,residence: FriendAddress) {
self.name = name
self.age = age
self.email = email
self.residence = residence
}
// NodeInitializable
init(node: Node, in context: Context) throws {
id = try node.extract("_id")
name = try node.extract("name")
age = try node.extract("age")
email = try node.extract("email")
residence = try node.extract("residence")
}
// NodeRepresentable
func makeNode(context: Context) throws -> Node {
return try Node(node: ["_id": id,
"name": name,
"age": age,
"email": email,
// "residence": residence
])
}
// Preparation
static func prepare(_ database: Database) throws {
try database.create("friends") { friends in
friends.id("_id")
friends.string("name")
friends.int("age")
friends.string("email")
friends.string("residence")
}
}
static func revert(_ database: Database) throws {
try database.delete("friends")
}
}
基本上需要一个这样的json结构,
basically need a json structure like this,
例如:
{
"name": "anil",
"age": 12,
" email": "anilklal91@gmail.com",
"residence": {
"address": "first address 1",
"address2": "second address 2",
"pinCode" : 110077
}
}
推荐答案
如果你想把模型变成 JSON,最好的方法是让你的模型符合 JSONRepresentable
.在这种情况下,您应该同时符合 Friend
和 FriendAddress
.
If you want to make a model into JSON, the best way is to conform your model to JSONRepresentable
. In this case, you should conform both Friend
and FriendAddress
.
为您的 Friend
模型实现它的可能方法:
A possible way to implement it for your Friend
model:
func makeJSON() throws -> JSON {
var json = JSON()
try json.set("name", name)
try json.set("age", age)
try json.set("email", email)
try json.set("residence", residence)
return json
}
请注意,它使用 FriendAddress
的 makeJSON()
实现嵌套 residence
.
Note that it nests residence
using FriendAddress
's implementation of makeJSON()
.
这篇关于如何使用 Mongokitten 在蒸汽中创建模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!