0

我正在尝试使用 ReactiveMongo 中指定的 _id 字段插入一个新文档。但是我所有的插入都是使用 Mongo 默认增量 objectId 执行的。有没有办法在插入期间指定_id?

这是我的代码。

case class MongoId($oid: String)

object MongoId {
  implicit val mongoIdFormat = Json.format[MongoId]
}

case class Person(_id: MongoId, name: String) 

object Person {
  implicit val PersonFormat = Json.format[Person]
}

val collection = reactiveMongoApi.database.map(_.collection[JSONCollection]("people"))

def save(person: Person) = {
  collection.flatMap(d => d.insert(person)).map(wr => wr.hasErrors match {
    case true => None
    case false => Some(person)
  })
}
4

1 回答 1

0

当然有办法。ObjectId在插入 MongoDB 之前,您需要自己生成。下面的例子。

case class Person (_id: BSONObjectID, name: String)

object Person {
   implicit val PersonFormat = Json.format[Person]
}

val p = Person(BSONObjectID.generate, "Mac")

save(p)
于 2016-11-15T08:56:52.163 回答