Scala, Mongodb with casbah + salat. Atomic operation

324 Views Asked by At

I have the following DAO method:

  /**
   * Delete a Program (hard delete), or mark as deleted (soft delete) 
   * will only hard-delete if:
   *   * No other program is based on this one
   *   * The program is not live
   */
  def delete(id: String) = {
    val oid = new ObjectId(id)

    //If we find any programs based on this one, soft delete
    if(ProgramDao.count(MongoDBObject("basedOn" -> oid)) > 0) {
      ProgramDao.collection.update(
        q = MongoDBObject("_id" -> oid), 
        o = MongoDBObject("deletedDate" -> DateTime.now().withTimeAtStartOfDay())
      )
    }
    else {
      ProgramDao.collection.findAndModify( //If we find this program has a liveDate, soft delete
        query = ("_id" $eq oid) ++ ("liveDate" $exists true), 
        update = MongoDBObject("deletedDate" -> DateTime.now().withTimeAtStartOfDay())
      ) match {
        case None => PersonDao.removeById(oid) //Otherwise hard delete
      }
    }
  }

The comment explains the rough idea. As you can see in the if block, it must first query the program collection to see if any programs have a reference to this one, then if there are any it goes and updates the record. In the else block the it tries to find a Program with the supplied id that is live, if it finds it it updates the record, otherwise it removes the record, as its deemed to not be live.

What id like to check is whether there is a better way of doing this (im new to noSQL), ideally atomically, but im open to any suggestions as this is my first attempt at something slightly complex!

Cheers! NFV

0

There are 0 best solutions below