任何人都可以帮我解决如何将模型(如用户(名称:字符串))转换为JSON并将其保存到MongoDB?
你可以试试这样的东西......
Build.sbt:
"org.mongodb.scala" %% "mongo-scala-driver" % "2.6.0"
"com.typesafe.play" %% "play-json" % "2.7.1"
首先创建mongoDB配置..
val credential: MongoCredential = ???
val settings: MongoClientSettings = ???
val client: MongoClient = MongoClient(settings)
val db: MongoDatabase = client.getDatabase("db-name")
val collection: MongoCollection[Document] = client.getCollection("collection-name")
case class Model(name: string)
object Model {
implicit val modelFormat: Format[Model] = Json.format[Model]
}
用法:
val data: JsValue = Json.toJson(new Model("Rex"))
插入db并检查是否插入:) ..
collection.insertOne(Document(data.toString))