Ruby / Mongoid -如何在集合中增加一个值并返回新值

icomxhvb  于 5个月前  发布在  Ruby
关注(0)|答案(2)|浏览(55)

我正在更新一些Ruby on Rails代码,这些代码使用了非常过时的Mongoid版本。我有以下代码行,它获取集合中的第一个文档,并将字段nextid递增1,然后返回新值:
surveyid = SurveyId.first.safely.inc(:nextid, 1)
我已经将Mongoid更新到6.0.3版本,它不再有safely方法。如果我只是用途:
surveyid = SurveyId.first.inc(:nextid, 1)
它可以工作,但是inc没有返回任何东西,我不知道新的值是什么。
新版本的Mongoid中的等效代码是什么?谢谢!

2hh7jdfx

2hh7jdfx1#

对于较新版本的Mongoid(7+):

surveyid = SurveyId.first.inc(nextid: 1).nextid

字符串
inc在操作成功时返回更新后的对象。

watbbzwu

watbbzwu2#

我想明白了。我找到了一个宝石,它确实是我想要的,叫做mongoid_auto_increment
现在我可以添加一个自动递增的字段到我的集合中,然后完成它。另外,这个Gem的source code说明了如何递增一个值并获得新值,尽管我没有真正深入研究它,因为我只是决定使用gem:

def inc
    if defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '5'
      collection.find(query).find_one_and_update({ '$inc' => { number: @step } }, new: true, upsert: true, return_document: :after)['number']
    elsif defined?(::Mongoid::VERSION) && ::Mongoid::VERSION >= '3'
      collection.find(query).modify({ '$inc' => { number: @step } }, new: true, upsert: true)['number']
    else
      opts = {
        "query"  => query,
        "update" => {"$inc" => { "number" => @step }},
        "new"    => true # return the modified document
      }
      collection.find_and_modify(opts)["number"]
    end
   end

字符串

相关问题