本文整理汇总了Scala中reactivemongo.api.commands.WriteResult类的典型用法代码示例。如果您正苦于以下问题:Scala WriteResult类的具体用法?Scala WriteResult怎么用?Scala WriteResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WriteResult类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: find
//设置package包名称以及导入依赖的类
package repos
import scala.concurrent.{ExecutionContext, Future}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import play.api.libs.json.{JsObject, Json}
import reactivemongo.api.commands.WriteResult
import play.modules.reactivemongo.ReactiveMongoApi
import javax.inject._
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.ReadPreference
trait PostRepo {
def find() (implicit ec: ExecutionContext): Future[List[JsObject]]
def select(selector: BSONDocument) (implicit ec: ExecutionContext): Future[Option[JsObject]]
def update(selector: BSONDocument, update: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
def remove(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
def save(document: BSONDocument) (implicit ec: ExecutionContext): Future[WriteResult]
}
class PostRepoImpl @Inject() (reactiveMongoApi: ReactiveMongoApi) extends PostRepo {
def collection = reactiveMongoApi.db.collection[JSONCollection]("posts");
override def find() (implicit ec: ExecutionContext): Future[List[JsObject]] = {
val genericQueryBuilder = collection.find(Json.obj());
val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary);
cursor.collect[List]()
}
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector,update)
}
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例2: find
//设置package包名称以及导入依赖的类
package repos
import javax.inject.Inject
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
trait RepoLike {
def find()(implicit ec: ExecutionContext): Future[List[JsObject]]
def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]]
def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
}
abstract class Repo @Inject()(reactiveMongoApi: ReactiveMongoApi) extends RepoLike {
val collectionName: String
override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
collection.find(Json.obj())
.cursor[JsObject](ReadPreference.Primary)
.collect[List](100)
}
override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector, update)
}
def collection: JSONCollection = reactiveMongoApi.db.collection[JSONCollection](collectionName)
override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例3: RecoveryPolicy
//设置package包名称以及导入依赖的类
// The MIT License (MIT)
// Copyright (c) 2016 Paul Lavery
//
// See the LICENCE.txt file distributed with this work for additional information regarding copyright ownership.
package utils
import play.api.Logger
import play.api.mvc.Result
import play.api.mvc.Results.{InternalServerError, Ok}
import play.api.libs.json.Json
import reactivemongo.api.commands.WriteResult
object RecoveryPolicy {
val defaultRecoveryPolicy: PartialFunction[Throwable, Result] = {
// If the result from Mongo is defined with the error code 11000 (duplicate error)
case duplicateResult: WriteResult if (duplicateResult.code contains 11000) =>
Ok(Json.obj("status" ->"KO", "message" -> "An object with same ID already exists"))
case errorResult: WriteResult =>
Logger.error(s"An error happened while trying to write to the DB: $errorResult.message")
InternalServerError(Json.obj("status" ->"KO", "message" -> "Oops something went wrong"))
case genericError =>
Logger.error(genericError.toString)
InternalServerError(Json.obj("status" ->"KO", "message" -> "Oops something went wrong"))
}
}
示例4: MongoPersistenceRepository
//设置package包名称以及导入依赖的类
package com.shop.db.persistence.mongo
import com.shop.db.persistence.PersistenceRepository
import play.api.Play._
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json.JSONSerializationPack.{Reader, Writer}
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.commands.WriteResult
import scala.concurrent.Future
abstract class MongoPersistenceRepository[A, B](implicit writer: Writer[B], reader: Reader[B]) extends PersistenceRepository[A, B] {
lazy val reactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
val collection: JSONCollection
override def save(model: B): Future[Unit] = {
collection.insert(model).map(validateResult(_))
}
override def update(id: A, model: B): Future[Unit] = {
collection.update(Json.obj("_id" -> id.toString), model).map(validateResult(_))
}
override def delete(id: A): Future[Unit] = {
collection.remove(Json.obj("_id" -> id.toString)).map(validateResult(_))
}
override def findById(id: A): Future[Option[B]] = {
collection.find(Json.obj("_id" -> id.toString)).one[B]
}
override def findAll(maxResults: Int = 100): Future[List[B]] = {
collection.find(Json.obj()).cursor[B]().collect[List](upTo = maxResults)
}
private def validateResult(writeResult: WriteResult): Unit = {
writeResult match {
case writeResult if writeResult.ok == true =>
case writeResult => throw writeResult.getCause
}
}
}
示例5: TranslatorRepositoryImpl
//设置package包名称以及导入依赖的类
package Repositories.implements
import Repositories.TranslatorRepository
import com.google.inject.Inject
import models.Translator
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.api.{QueryOpts, ReadPreference}
import reactivemongo.api.commands.WriteResult
import reactivemongo.play.json.collection.JSONCollection
import utils.Pagination
import play.modules.reactivemongo.json._
import scala.concurrent.{ExecutionContext, Future}
class TranslatorRepositoryImpl @Inject()(reactiveMongoApi: ReactiveMongoApi) extends TranslatorRepository{
def collection(implicit ec: ExecutionContext) = reactiveMongoApi.database.map(_.collection[JSONCollection]("translators"))
override def getAllTranslators(pagination: Pagination, sortField: String)(implicit ec: ExecutionContext): Future[List[JsObject]] = {
var sort : Int = 1; var getField: String = sortField
if(sortField.startsWith("-")){
sort = -1; getField = sortField.drop(1)
}
val genericQueryBuilder = collection.map(_.find(Json.obj()).sort(Json.obj(getField -> sort)).options(QueryOpts(pagination.Offset)))
val cursor = genericQueryBuilder.map(_.cursor[JsObject](ReadPreference.Primary))
cursor.flatMap(_.collect[List](pagination.Limit))
}
override def insertTranslator(translator: Translator)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.flatMap(_.insert(translator))
}
override def count()(implicit ec: ExecutionContext): Future[Int] = {
val count = collection.flatMap(_.count()); count
}
}
示例6: MongoBillingDetailsRepository
//设置package包名称以及导入依赖的类
package com.lej.customer.infrastructure.persistence
import javax.inject.Inject
import com.lej.customer.domain.model.BillingDetailsRepository
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
class MongoBillingDetailsRepository @Inject()(reactiveMongoApi: ReactiveMongoApi) extends BillingDetailsRepository {
def collection = reactiveMongoApi.db.collection[JSONCollection]("billing_details")
override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
val genericQueryBuilder = collection.find(Json.obj())
val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary)
cursor.collect[List]()
}
override def select(selector: BSONDocument)(implicit ec: ExecutionContext): Future[Option[JsObject]] = {
collection.find(selector).one[JsObject]
}
override def update(selector: BSONDocument, update: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(selector, update)
}
override def remove(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.remove(document)
}
override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例7: save
//设置package包名称以及导入依赖的类
package io.github.bszwej.core.repository
import com.typesafe.scalalogging.LazyLogging
import io.github.bszwej.MainConfig
import io.github.bszwej.core.exception.{MongoException, MongoWriteException}
import io.github.bszwej.core.model.Tweet
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.BSONDocument
import scala.concurrent.{ExecutionContext, Future}
def save(tweet: Tweet): Future[RepositorySuccess.type]
}
case object RepositorySuccess
class MongoTweetRepository(collection: Future[BSONCollection])(implicit ec: ExecutionContext) extends TweetRepository with LazyLogging with MainConfig {
override def save(tweet: Tweet): Future[RepositorySuccess.type] = {
val document = BSONDocument(
"username" ? tweet.username,
"message" ? tweet.message,
"hashtag" ? tweet.hashtag
)
collection.flatMap(_.insert(document).map(_ ? RepositorySuccess)) recoverWith {
case WriteResult.Message(message) ?
logger.error(s"Error during storing a tweet: $message.")
Future.failed(new MongoWriteException(message))
case e: Exception ?
logger.error(s"Error during storing a tweet: ${e.getMessage}.")
Future.failed(new MongoException(e.getMessage))
}
}
}
示例8: PlaceDAO
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.google.common.io.Files
import models.{Place, PlaceData}
import play.api.data.Form
import play.api.data.Forms._
import play.api.libs.Files.TemporaryFile
import play.api.libs.json.Json
import play.api.mvc.Controller
import play.api.mvc.MultipartFormData.FilePart
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.commands.WriteResult
import reactivemongo.api.{Cursor, ReadPreference}
import reactivemongo.play.json.collection.JSONCollection
import scala.concurrent.{ExecutionContext, Future}
class PlaceDAO @Inject() (val reactiveMongoApi: ReactiveMongoApi)
(implicit ec: ExecutionContext)
extends Controller with MongoController with ReactiveMongoComponents{
def create(placeData: PlaceData, picture: FilePart[TemporaryFile]): Future[WriteResult] = {
placesCollection.flatMap(_.insert(Place(placeData.name, placeData.country, placeData.description,
Files.toByteArray(picture.ref.file))))
}
def all(): Future[List[Place]] = placesCollection.flatMap(_.find(Json.obj())
.cursor[Place](ReadPreference.primaryPreferred).collect[List](Int.MaxValue, Cursor.FailOnError[List[Place]]()))
def placesCollection: Future[JSONCollection] = database.map(_.collection[JSONCollection]("places"))
}
object PlaceDAO {
val createPlaceForm = Form(
mapping(
"name" -> nonEmptyText,
"country" -> nonEmptyText,
"description" -> nonEmptyText
)(PlaceData.apply)(PlaceData.unapply)
)
}
示例9: ValorationDAO
//设置package包名称以及导入依赖的类
package dao.impl
import play.api.libs.json.{ JsObject, Json }
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{ BSONObjectID, BSONDocument }
import play.modules.reactivemongo.ReactiveMongoApi
import reactivemongo.bson.{ BSONObjectID, BSONDocument }
import scala.concurrent.{ ExecutionContext, Future }
import dao.TValorationDAO
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.json.BSONDocumentWrites
import play.modules.reactivemongo.json.JsObjectDocumentWriter
import reactivemongo.bson.Producer.nameValue2Producer
import scala.annotation.implicitNotFound
class ValorationDAO(reactiveMongoApi: ReactiveMongoApi) extends TValorationDAO {
// BSON-JSON conversions
import play.modules.reactivemongo.json._
protected def collection =
reactiveMongoApi.db.collection[JSONCollection]("valorations")
def uuid = java.util.UUID.randomUUID.toString
def find()(implicit ec: ExecutionContext): Future[List[JsObject]] =
collection.find(Json.obj()).cursor[JsObject](ReadPreference.Primary).collect[List]()
def findBySpot(spotId: String)(implicit ec: ExecutionContext): Future[List[JsObject]] =
collection.find(BSONDocument("spot_id" -> spotId)).cursor[JsObject]().collect[List]()
def findById(genId: String)(implicit ec: ExecutionContext): Future[Option[JsObject]] =
collection.find(BSONDocument("_id" -> genId)).one[JsObject]
def findById2(genId: String)(implicit ec: ExecutionContext): Future[Option[BSONDocument]] =
collection.find(BSONDocument("_id" -> genId)).one[BSONDocument]
def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] =
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
示例10: OcrRepository
//设置package包名称以及导入依赖的类
package repository
import model.{OcrEntity, OcrTextOnly}
import reactivemongo.api.Cursor
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONRegex}
import scala.concurrent.Future
class OcrRepository extends MongoDao[OcrEntity] {
lazy val collectionFuture: Future[BSONCollection] = dbFuture.map(db => db[BSONCollection]("ocr"))
def save(ocrEntity: OcrEntity): Future[OcrEntity] = save(collectionFuture, ocrEntity)
def deleteById(id: String): Future[WriteResult] = deleteById(collectionFuture, id)
def findById(id: String): Future[Option[OcrEntity]] = find(collectionFuture, queryById(id))
def findTextOnlyForUserId(userId: String, query: String): Future[List[OcrTextOnly]] =
collectionFuture.flatMap(
_.find(BSONDocument(
"userId" -> userId,
"result.text" -> BSONRegex(query, "i")
),
BSONDocument("result.text" -> 1))
.cursor[OcrTextOnly]()
.collect[List](-1, Cursor.FailOnError[List[OcrTextOnly]]()))
}
示例11: playerDao
//设置package包名称以及导入依赖的类
package dao
import javax.inject._
import play.modules.reactivemongo._
import play.api.libs.concurrent.Execution.Implicits._
import scala.concurrent._
import models.PlayerModel
import reactivemongo.api.commands.WriteResult
import reactivemongo.api.collections.bson._
import reactivemongo.bson._
import reactivemongo.api.commands.UpdateWriteResult
@Singleton
class playerDao @Inject()(val reactiveMongoApi: ReactiveMongoApi) {
def collection: Future[BSONCollection] = reactiveMongoApi.database.map(_.collection[BSONCollection]("player"))
def createNewPlayer(player: PlayerModel) : Future[UpdateWriteResult] = {
val query = BSONDocument("name" -> player.name)
val update = BSONDocument("$setOnInsert" -> player)
collection flatMap ( _.update(query,update,upsert=true) )
}
def find(name: String) : Future[Option[PlayerModel]] = {
val query = BSONDocument("name" -> name)
collection flatMap ( _.find(query).one[PlayerModel] )
}
}
示例12: BaseModelDAO
//设置package包名称以及导入依赖的类
package models.daos
import scala.concurrent.Future
import models.DbModel
import models.JsonImpl
import reactivemongo.play.json.collection.JSONCollection
import play.api.libs.json.JsObject
import scala.concurrent.ExecutionContext
import play.api.libs.json.Json
import play.api.libs.json.Reads
import play.api.libs.json.OWrites
import reactivemongo.api.commands.WriteResult
import reactivemongo.play.json.JSONSerializationPack
import play.modules.reactivemongo.json._
import reactivemongo.api.QueryOpts
import models.DbModelComp
abstract class BaseModelDAO[M <: DbModel with JsonImpl](implicit exec: ExecutionContext, implicit val joWrites: OWrites[M],
implicit val joReads: Reads[M]) {
protected def collection: Future[JSONCollection]
protected val companionObject: DbModelComp[M]
final def insert(model: M): Future[WriteResult] = collection.flatMap { collection => collection.insert(model) }
final def update(model: M): Future[WriteResult] = collection.flatMap(collection => {
val query = companionObject.queryByUuid(model.uuid)
collection.update(query, companionObject.getUpdateObject(model))
})
final def remove(model: M): Future[Boolean] = collection.flatMap(_.remove(companionObject.queryByUuid(model.uuid)).
map { wr => wr.ok })
final def count(query: JsObject): Future[Int] = collection.flatMap(_.count(Some(query)))
final def findOneByUuid(uuid: String): Future[Option[M]] = find(companionObject.queryByUuid(uuid), 1, 1).map(_.headOption)
final def find(query: JsObject, page: Int, pageSize: Int): Future[List[M]] =
collection.flatMap(_.find(query).options(QueryOpts((page - 1) * pageSize, pageSize)).cursor[M]().
collect[List](pageSize))
final def findAndSort(query: JsObject, sort: JsObject, page: Int, pageSize: Int): Future[List[M]] =
collection.flatMap(_.find(query).sort(sort).options(QueryOpts((page - 1) * pageSize, pageSize)).cursor[M]().
collect[List](pageSize))
}
示例13: find
//设置package包名称以及导入依赖的类
package repos
import javax.inject.Inject
import play.api.libs.json.{JsObject, Json}
import play.modules.reactivemongo.ReactiveMongoApi
import play.modules.reactivemongo.json._
import play.modules.reactivemongo.json.collection.JSONCollection
import reactivemongo.api.ReadPreference
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import scala.concurrent.{ExecutionContext, Future}
trait ApiRepo {
def find()(implicit ec: ExecutionContext): Future[List[JsObject]]
def save(selector: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult]
}
class MongoApiRepo @Inject()(reactiveMongoApi: ReactiveMongoApi) extends ApiRepo {
def collection = reactiveMongoApi.db.collection[JSONCollection]("users")
override def find()(implicit ec: ExecutionContext): Future[List[JsObject]] = {
val genericQueryBuilder = collection.find(Json.obj())
val cursor = genericQueryBuilder.cursor[JsObject](ReadPreference.Primary)
cursor.collect[List]()
}
override def save(document: BSONDocument)(implicit ec: ExecutionContext): Future[WriteResult] = {
collection.update(BSONDocument("_id" -> document.get("_id").getOrElse(BSONObjectID.generate)), document, upsert = true)
}
}
示例14: insert
//设置package包名称以及导入依赖的类
package org.cristal.repository.dao
import org.cristal.model.User
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.WriteResult
import reactivemongo.bson.BSONDocument
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
trait UserDAO {
def insert(user: User): Future[Unit]
}
class UserDAOImpl(implicit executor: ExecutionContext) extends UserDAO with UserCollection {
override def insert(user: User) = handleInsertResult(
usersCollection.flatMap(_.insert(userToDocument(user))))
private def handleInsertResult(result: Future[WriteResult]) = {
result.onComplete {
case failure @ Failure(e) => e.printStackTrace(); failure
case Success(_) => println(s"User successfully inserted.")
}
result.map(_ => ())
}
def usersCollection : Future[BSONCollection] = db.map(_.collection("users"))
def userToDocument(user: User) = BSONDocument(
"username" -> user.username,
"password" -> user.password,
"first_name" -> user.firstName,
"last_name" -> user.lastName,
"email" -> user.email
)
}
trait UserCollection extends DBConnection {
}