How to create a model in vapor using Mongokitten

2019-09-17 02:33发布

问题:

This is the model and I have to change it to mongo model using mongokitten.

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")
        }
    }

basically need a json structure like this,

for eg:

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

回答1:

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.

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
}

Note that it nests residence using FriendAddress's implementation of makeJSON().