mongodb - Nested queries with ReactiveMongo -
i have article collection fields "title" , "publication" has unique combined key constraint.
when calling insertorupdatearticle(a: article) first try insert it, in case hits constraint, should update article - if needed.
however, i'm stuck before that. current error is:
error:(88, 57) type mismatch; found : scala.concurrent.future[scala.concurrent.future[boolean]] required: boolean col_article.find(selector).one[article].map {
source:
def insertorupdatearticle(a: article): future[boolean] = { // try insert article col_article.insert[article](a).map { // article inserted lasterror => { println("article added.") true } }.recover { case lasterror: lasterror => // check if article existed lasterror.code.get match { case 11000 => { // article existed (duplicate key error) // load old article val selector = bsondocument( "title" -> bsonstring(a.title), "publication" -> bsonstring(a.publication) ) col_article.find(selector).one[article].map { case some(old_a: article) => { // todo: compare old_a // todo: if differs old_a, update future(true) } case none => { // went wrong future(false) } } } case _ => { println("db.insertorupdatearticle() unexpected error code when inserting: " + lasterror.code.get) false } } case ex => println("db.insertorupdatearticle() unexpected exception when inserting: " + ex) false } }
i'm unsure here. code should return future(true) if article saved or updated, false otherwise. there's reactivemongo and/or scala futures i'm missing out here.
using recoverwith create new future solution, modified code:
def insertorupdatearticleold(a: article): future[boolean] = { // try insert article col_article.insert[article](a).map { // article inserted lasterror => { println("article added.") true } }.recoverwith { case lasterror: lasterror => // check if article existed lasterror.code.get match { case 11000 => { // article existed (duplicate key error) // load old article val selector = bsondocument( "title" -> bsonstring(a.title), "publication" -> bsonstring(a.publication) ) col_article.find(selector).one[article].flatmap { case some(old_a: article) => { // todo: compare old_a // todo: if differs old_a, update future(true) } case none => { // went wrong future(false) } } } case _ => { println("db.insertorupdatearticle() unexpected error code when inserting: " + lasterror.code.get) future(false) } } case ex => println("db.insertorupdatearticle() unexpected exception when inserting: " + ex) future(false) } }
Comments
Post a Comment