如何获取最后插入的ID? 我需要获得最新评论ID。请参阅以下代码:
Snoop.findOneById(snoopId) match {
case Some(snoop) => {
user.groups.find(ug => ug.groupId == snoop.groupId).map { ug =>
val prop = Property.findOneById(snoop.propertyId).get
val comment = Comment(userId = user.id, name=user.getNameString, text = text)
val snoopSave = snoop.copy(comments = comment :: snoop.comments)
val sComment = Snoop.save(snoopSave)
}
.getOrElse(None)
}
case _ => None
}
Mongodb结构:
{
"_id": ObjectId("532725c3ff5d00682f5a0b9b"),
"_t": "models.Snoop",
"propertyId": ObjectId("532725bfff5d00682f5a0b99"),
"groupId": ObjectId("529f6461e4b008b565b4358c"),
"userId": ObjectId("532717e5ff5d00682f5a0b83"),
"price": 995000,
"monthlyFees": 0,
"comments": {
"0": {
"_t": "models.Comment",
"_id": ObjectId("534bce0b7d374bf1b5a170ba"),
"userId": ObjectId("529f6461e4b008b565b4358b"),
"name": "monmon",
"text": "test",
"createDate": ISODate("2014-04-14T12: 01: 15.627Z"),
"replies": {
"0": {
"_t": "models.Comment",
"_id": ObjectId("534bd1b67d374bf1b5a170be"),
"userId": ObjectId("529f6461e4b008b565b4358b"),
"name": "monmon",
"text": "monnmonn",
"createDate": ISODate("2014-04-14T12: 16: 54.752Z"),
"replies": [
]
},
"1": {
"_t": "models.Comment",
"_id": ObjectId("534bcf437d374bf1b5a170bc"),
"userId": ObjectId("529f6461e4b008b565b4358b"),
"name": "monmon",
"text": "test test test",
"createDate": ISODate("2014-04-14T12: 06: 27.896Z"),
"replies": [
]
}
}
}
}
另外,我尝试了Get ID of last inserted document in a mongoDB w/ Java driver,但没有效果:
val sComment = Snoop.save(snoopSave)
ObjectId id = (ObjectId)sComment.get( "_id" );
答案 0 :(得分:0)
不想回答这个问题,但可能会帮助别人!
- 根据我的研究,mongodb生成的ID是通过客户端完成的,所以不需要查询到服务器端
解决方案#1 为您的ID分配值
EX: val cID = new Object()
然后将其包含在您的保存代码中
解决方案#2 让mongodb分配ID
EX: val comment = Comment(userId = user.id, name=user.getNameString, text = text)
然后,这将返回所有信息以及生成的ID。你可以访问 ID通过comment.id(在我的情况下)。
希望这会有助于其他人