json操纵并推送到mongodb(PLAY-2.7-Scala-2.12)

问题描述 投票:-3回答:1

任何人都可以帮我解决如何将模型(如用户(名称:字符串))转换为JSON并将其保存到MongoDB?

json mongodb scala playframework
1个回答
0
投票

你可以试试这样的东西......

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

© www.soinside.com 2019 - 2024. All rights reserved.