2017-04-24 46 views
0

這是模型,我必須使用mongokitten將其更改爲mongo模型。如何使用Mongokitten創建蒸氣模型

這是我的朋友模型,我已經實施。 這但不能爲這個模式做一個像結構一樣的嵌套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": "[email protected]", 
    "residence": { 
    "address": "first address 1", 
    "address2": "second address 2", 
    "pinCode" : 110077 
    } 
} 
+0

歡迎來到Stack Overflow!看起來你需要更多地瞭解這裏用戶的期望。您需要嘗試自己編寫代碼。如果您遇到問題,請在進行更多研究之後,您可以發佈您已嘗試過的內容並清楚說明哪些內容無法正常工作並提供[MCVE]。我建議閱讀[問]。 –

+0

@DavidGlickman我已經嘗試和編輯的職位參考..需要幫助實現問題的解決方案,不期望代碼爲我..謝謝 –

回答

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 
} 

注意,它使用FriendAddress的實施makeJSON()residence