auto incerement field in mongodb

145 views
Skip to first unread message

Vinnakota Priyatam Sai

unread,
Jan 14, 2016, 6:20:52 AM1/14/16
to ReactiveMongo - http://reactivemongo.org
I have some MySQL legacy, so I need to keep an auto increment field into my MongoDB collection.

> db.system.js.find({})
{ "_id" : "getNextSequence", "value" : function (sequenceName) {
   var sequenceDocument = db.counters.findAndModify({
      query:{_id: sequenceName },
      update: {$inc:{sequence_value:1}},
      new:true
   });
   return sequenceDocument.sequence_value;
} }

I have saved getNextSequence function in my mongodb as shown above. How do I call this getNextSequence function from scala?
 I'm trying to use BSONJavaScript to call mongodb function in my writes, but doesn't work, saying 'unhandled json value'.(check attached file)

InfoCards.scala (model)

case class InfoCards (
id : Option[BSONObjectID] = None,
card_type : String,
title : String,
sub_text : String,
info : List[Info],
link_text : String,
link_url : String,
card_id : Int
)


object InfoCards {

implicit object InfoCardWrites extends OWrites[InfoCards] {
def writes(cardinfo: InfoCards) : JsObject = Json.obj(
"_id" -> BSONObjectIDFormat.partialWrites(cardinfo.id.getOrElse(BSONObjectID.generate)),
"card_type" -> cardinfo.card_type,
"title" -> cardinfo.title,
"sub_text" -> cardinfo.sub_text,
"info" -> cardinfo.info,
"link_text" -> cardinfo.link_text,
"link_url" -> cardinfo.link_url,
"card_id" -> BSONJavaScript("getNextSequence(\"cards\")") //Error
)
}

implicit object InfoCardReads extends Reads[InfoCards] {
def reads(json: JsValue): JsResult[InfoCards] = json match {
case obj: JsObject => try {
val id = (obj \ "_id").asOpt[BSONObjectID]
val card_type = (obj \ "card_type").as[String]
val title = (obj \ "title").as[String]
val sub_text = (obj \ "sub_text").as[String]
val info = (obj \ "info").as[List[Info]]
val link_text = (obj \ "link_text").as[String]
val link_url = (obj \ "link_url").as[String]
val card_id = (obj \ "card_id").as[Int]
JsSuccess(InfoCards(id, card_type, title, sub_text, info, link_text, link_url, card_id))
}
catch {
case cause: Throwable =>JsError(cause.getMessage)
}
case _ => JsError("expected.jsobject")
}
}

}
error.png

Cédric Chantepie

unread,
Jan 16, 2016, 7:31:52 AM1/16/16
to ReactiveMongo - http://reactivemongo.org
Hi, you can try with
"org.reactivemongo" % "reactivemongo-play-json_2.11" % "0.12.0-SNAPSHOT" .
Reply all
Reply to author
Forward
0 new messages