如何使用Mongokitten在蒸汽中创建模型

时间:2017-04-24 12:43:44

标签: mongodb swift3 vapor

这是模型,我必须使用mongokitten将其更改为mongo模型。

这是我的朋友模特,我已经实施了。 这个但不能为这种模式制作嵌套的json结构。

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结构,

例如:

{    
"name": "anil",
 "age": 12,
  "   email": "anilklal91@gmail.com",
     "residence": {
    "address": "first address 1",
    "address2": "second address 2",
    "pinCode" : 110077
     }
 }

1 个答案:

答案 0 :(得分:0)

如果您想将模型制作成JSON,最好的方法是使您的模型符合JSONRepresentable。在这种情况下,您应该同时遵守FriendFriendAddress

Friend模型实现此功能的可能方法:

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
}

请注意,它使用residence FriendAddress的{​​{1}}实现makeJSON()。{/ p>

相关问题