2011-06-28 10 views
1

組み込みドキュメントで原子修飾子を使用する方法については、いくつかの助けが必要です。埋め込みドキュメントのMongoDB/MongoMapper修飾子

説明すると、私はこのようなコレクションがあると仮定しましょう。私はMongoMapper/MongoDBのをどうしているよ何

投稿コレクション

{ 
    "_id" : ObjectId("blah"), 
    "title" : "Some title", 
    "comments" : [ 
    { 
     "_id" : ObjectId("bleh"), 
     "text" : "Some comment text", 
     "score" : 0, 
     "voters" : [] 
    } 
    ] 
} 

はポスト文書内の特定のコメントのアトミック更新を行うことです。私が今持っているものは基本的だし、それが(何も更新されなかっます)すべてで動作していない

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の埋め込みドキュメントを使用してこれを行う方法はないようです。私が間違ってやっていることについてのどんな考えですか?

答えて

2

興味のある方はこれを手に入れてください。私は

  • $inc$演算子を使用した(USER_IDが含まれていないように_id =「」AND有権者など)の二つの条件を満足する必要があり、配列内のオブジェクトを検索する$elemMatchを使用し

    1. を行方不明になった二つのことおよび$push操作を使用して、自分のクエリで参照される特定のオブジェクトを変更していることを確認します。

    def upvote!(user_id) 
        # Use the Ruby Mongo driver to make a direct call to collection.update 
        collection.update(
        { 
         'meanings' => { 
         '$elemMatch' => { 
          '_id' => self.id, 
          'voters' => {'$ne' => user_id} 
         } 
         } 
        }, 
        { 
         '$inc' => { 'meanings.$.votes' => 1 }, 
         '$push' => { 'meanings.$.voters' => user_id } 
        }) 
    end 
    
  • 関連する問題