Scala ReactiveMongo 示例。遗漏操作或隐式
Scala ReactiveMongo example. Missed operations or implicits
我正在尝试使用 reactivemongo getstarted 来研究如何使用它。我使用:
- scala 2.13.0
"org.reactivemongo" %% "reactivemongo" % "0.18.6"
对我来说,我已经按照文档要求完成了。但是编译问题出现在每个数据库操作附近(personCollection
:insert
、update
、find
)。由于缺少 scala knowledge\experience.
,我不清楚如何修复它们
代码:
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Try
import reactivemongo.api.{Cursor, DefaultDB, MongoConnection, MongoDriver}
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter, Macros, document}
object GetStartedWithMongo {
def main(args: Array[String]): Unit = {
val age = 99
val person: Person = Person("firstName", "lastName", age)
createPerson(person)
findPersonByAge(age).andThen {
case x => println(s"loaded data: $x")
}
println("completed")
}
val database = "personDb"
val driver = new MongoDriver
val mongoUri = "mongodb://localhost:27017/mydb?authMode=scram-sha1"
// Connect to the database: Must be done only once per application
val parsedUri: Try[MongoConnection.ParsedURI] =
MongoConnection.parseURI(mongoUri)
val connection: Try[MongoConnection] = parsedUri.map(driver.connection(_))
val futureConnection: Future[MongoConnection] = Future.fromTry(connection)
// val db = connection(database)
val db: Future[DefaultDB] = futureConnection.flatMap(_.database(database))
// def personCollection: Future[List[Person]] = db.map(_.collection("person"))
def personCollection = db.map(_.collection("person"))
// use personWriter
def createPerson(person: Person): Future[Unit] =
personCollection.flatMap(_.insert.one(person).map(_ => {}))
// ^^^^^^ - compilation issue
// Write Documents: insert or update
implicit def personWriter: BSONDocumentWriter[Person] = Macros.writer[Person]
// or provide a custom one
def updatePerson(person: Person): Future[Int] = {
val selector =
document("firstName" -> person.firstName, "lastName" -> person.lastName)
// Update the matching person
personCollection.flatMap(_.update.one(selector, person).map(_.n))
// ^^^^^^ - compilation issue
}
implicit def personReader: BSONDocumentReader[Person] = Macros.reader[Person]
// or provide a custom one
def findPersonByAge(age: Int): Future[List[Person]] =
personCollection.flatMap(
_.find(document("age" -> age)). // query builder
// ^^^^ - compilation issue
cursor[Person](). // using the result cursor
collect[List](-1, Cursor.FailOnError[List[Person]]())
)
// ... deserializes the document using personReader
// Custom persistent types
case class Person(firstName: String, lastName: String, age: Int)
}
P.S.
要使其编译,请向 personCollection
添加显式类型注释:
def personCollection: Future[BSONCollection] = db.map(db => db.collection("person"))
检查其他 reactivemongo
教程页面,我们可以指定 dbCollection 类型。 Return 类型不是 Future[List[Person]]
或 Future[Person]
或 Future[Nothing]
。它是 Future[BSONCollection]。如果添加类型,编译问题已修复。
启动项目,我们可以在终端消息中找到其他遗漏的内容。为了修复丢失的依赖项,我添加到项目 slf4j
库 ("org.slf4j" % "slf4j-api" % "1.7.28"
)
所以如果我试试这个:
def main(args: Array[String]): Unit = {
val age = 93
val person: Person = Person("firstName", "lastName", age)
createPerson(person)
findPersonByAge(age).andThen {
case x => println(s"loaded data: $x")
}
println("completed")
}
总体上符合预期的结果:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
completed
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
loaded data: Success(List(Person(firstName,lastName,93)))
我正在尝试使用 reactivemongo getstarted 来研究如何使用它。我使用:
- scala 2.13.0
"org.reactivemongo" %% "reactivemongo" % "0.18.6"
对我来说,我已经按照文档要求完成了。但是编译问题出现在每个数据库操作附近(personCollection
:insert
、update
、find
)。由于缺少 scala knowledge\experience.
代码:
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.Try
import reactivemongo.api.{Cursor, DefaultDB, MongoConnection, MongoDriver}
import reactivemongo.bson.{BSONDocumentReader, BSONDocumentWriter, Macros, document}
object GetStartedWithMongo {
def main(args: Array[String]): Unit = {
val age = 99
val person: Person = Person("firstName", "lastName", age)
createPerson(person)
findPersonByAge(age).andThen {
case x => println(s"loaded data: $x")
}
println("completed")
}
val database = "personDb"
val driver = new MongoDriver
val mongoUri = "mongodb://localhost:27017/mydb?authMode=scram-sha1"
// Connect to the database: Must be done only once per application
val parsedUri: Try[MongoConnection.ParsedURI] =
MongoConnection.parseURI(mongoUri)
val connection: Try[MongoConnection] = parsedUri.map(driver.connection(_))
val futureConnection: Future[MongoConnection] = Future.fromTry(connection)
// val db = connection(database)
val db: Future[DefaultDB] = futureConnection.flatMap(_.database(database))
// def personCollection: Future[List[Person]] = db.map(_.collection("person"))
def personCollection = db.map(_.collection("person"))
// use personWriter
def createPerson(person: Person): Future[Unit] =
personCollection.flatMap(_.insert.one(person).map(_ => {}))
// ^^^^^^ - compilation issue
// Write Documents: insert or update
implicit def personWriter: BSONDocumentWriter[Person] = Macros.writer[Person]
// or provide a custom one
def updatePerson(person: Person): Future[Int] = {
val selector =
document("firstName" -> person.firstName, "lastName" -> person.lastName)
// Update the matching person
personCollection.flatMap(_.update.one(selector, person).map(_.n))
// ^^^^^^ - compilation issue
}
implicit def personReader: BSONDocumentReader[Person] = Macros.reader[Person]
// or provide a custom one
def findPersonByAge(age: Int): Future[List[Person]] =
personCollection.flatMap(
_.find(document("age" -> age)). // query builder
// ^^^^ - compilation issue
cursor[Person](). // using the result cursor
collect[List](-1, Cursor.FailOnError[List[Person]]())
)
// ... deserializes the document using personReader
// Custom persistent types
case class Person(firstName: String, lastName: String, age: Int)
}
P.S.
要使其编译,请向 personCollection
添加显式类型注释:
def personCollection: Future[BSONCollection] = db.map(db => db.collection("person"))
检查其他 reactivemongo
教程页面,我们可以指定 dbCollection 类型。 Return 类型不是 Future[List[Person]]
或 Future[Person]
或 Future[Nothing]
。它是 Future[BSONCollection]。如果添加类型,编译问题已修复。
启动项目,我们可以在终端消息中找到其他遗漏的内容。为了修复丢失的依赖项,我添加到项目 slf4j
库 ("org.slf4j" % "slf4j-api" % "1.7.28"
)
所以如果我试试这个:
def main(args: Array[String]): Unit = {
val age = 93
val person: Person = Person("firstName", "lastName", age)
createPerson(person)
findPersonByAge(age).andThen {
case x => println(s"loaded data: $x")
}
println("completed")
}
总体上符合预期的结果:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
completed
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
loaded data: Success(List(Person(firstName,lastName,93)))