嵌入式文档上的 MongoDB/MongoMapper 修饰符
需要一些有关如何在嵌入文档上使用原子修饰符的帮助。
为了说明这一点,我们假设我有一个如下所示的集合。
帖子集合
{
"_id" : ObjectId("blah"),
"title" : "Some title",
"comments" : [
{
"_id" : ObjectId("bleh"),
"text" : "Some comment text",
"score" : 0,
"voters" : []
}
]
}
我希望使用 MongoMapper/MongoDB 做的是对帖子文档中的特定评论执行原子更新。
就像:
class Comment
include MongoMapper::EmbeddedDocument
# Other stuff...
# For the current comment that doesn't have the current user voting, increment the vote score and add that user to the voters array so they can't vote again
def upvote!(user_id)
collection.update({"comments._id" => post_id, "comments.voters" => {"$ne" => user_id}},
{"$inc" => {"comments.score" => 1}, "$push" => {"comments.voters" => user_id}})
end
end
这基本上就是我现在所拥有的,但它根本不起作用(没有任何更新)。理想情况下,我还想重新加载文档/嵌入文档,但似乎没有办法使用 MongoMapper 的嵌入文档来做到这一点。关于我做错了什么有什么想法吗?
Need some help with how to use atomic modifiers on an embedded document.
To illustrate, let's assume I've got a collection that looks like this.
Posts Collection
{
"_id" : ObjectId("blah"),
"title" : "Some title",
"comments" : [
{
"_id" : ObjectId("bleh"),
"text" : "Some comment text",
"score" : 0,
"voters" : []
}
]
}
What I'm looking to do with MongoMapper/MongoDB is perform an atomic update on a specific comment within a post document.
Something like:
class Comment
include MongoMapper::EmbeddedDocument
# Other stuff...
# For the current comment that doesn't have the current user voting, increment the vote score and add that user to the voters array so they can't vote again
def upvote!(user_id)
collection.update({"comments._id" => post_id, "comments.voters" => {"$ne" => user_id}},
{"$inc" => {"comments.score" => 1}, "$push" => {"comments.voters" => user_id}})
end
end
That's basically what I have now and it isn't working at all (nothing gets updated). Ideally, I'd also want to reload the document / embedded document but it seems as though there may not be a way to do this using MongoMapper's embedded document. Any ideas as to what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让这个对任何感兴趣的人都有效。我错过了两件事
$elemMatch
搜索数组中需要满足两个条件的对象(例如 _id = "" AND voters 不包含 user_id)$$inc
和$push
操作上的 code> 运算符,以确保我正在修改查询引用的特定对象。Got this working for anyone that's interested. Two things I was missing
$elemMatch
to search objects within an array that need to satisfy two conditions (such as _id = "" AND voters DOES NOT contain the user_id)$
operator on the$inc
and$push
operations to ensure I'm modifying the specific object that's referenced by my query.