0

i need to return newly inserted object. I read that i can generate my own id but that's not probably the case.

def create(repo: String) = Action.async(parse.json) { implicit req =>
    val id = BSONObjectID.generate
    collection(repo).insert($("_id " -> id)).map { last =>
      if(last.ok)
        Ok(Json.toJson($("_id"->id)++$("success"->true)))
      else
        BadRequest($("success"->false))
    }
} 

And i'm generating records like this:

{
    "_id": {
        "$oid": "556dfb2021c76e3b1c566915"
    },
    "_id ": {
        "$oid": "556dfb1f5f00006100d4a0bc"
    }
}
Haito
  • 2,039
  • 1
  • 24
  • 35

2 Answers2

2

You should not generate MongoDB _id manually unless you know for sure that they are unique or you will have to deal with duplicated key exception in your code.

If you insert a new document without _id, MongoDB will generate one for you during the insert process. Then if you want this _id back, you can request MongoDB to get back your document with your newly created _id.

Normally the drivers handle this part automatically for you.

Maxime Beugnet
  • 822
  • 5
  • 10
  • You say "**Then if you want this _id back, you can request MongoDB to get back your document with your newly created _id**" but how exactly do you do this? The whole point is that you won't know the `_id` to make such a query – jesus g_force Harris Sep 13 '18 at 10:05
0

Just missclick, i added space by mistake to _id, and that was causing all the problems

Haito
  • 2,039
  • 1
  • 24
  • 35