Mongoid 5: find_one_and_update with returnNewDocument

Mongoid 5: find_one_and_update with returnNewDocument

Mongoid v5.1.2 是否有可能在与 find_one_and_update 一起使用时忽略 returnNewDocument 选项?

考虑以下代码:

next_number = TrackingId.where(id: id).find_one_and_update({
    :$inc => {
      auto_increment_counter: 1
    }
  },
  upsert: true,
  returnNewDocument: true
).auto_increment_counter

其中 auto_increment_counter 是 class 上的整数 field :auto_increment_counter, type: Integer, default: 0

但是,当找不到文档时,它会创建一个,但不会 return 新创建的文档。所以我从 find_one_and_update 返回 nil 并且它中断了。

我怀疑 find_one_and_update 的 mongoid 实现会将 returnNewDocument 的标志更改为 return_new_document 或 $returnNewDocument。稍后我会看一下 mongoid 代码库并确认。

更新:所以我偷偷摸摸地看了看代码。后来我也能够在文档中确认这一点。您要查找的选项是 return_document,您将其设置为 :before 或 :after(请参阅文档:http://www.rubydoc.info/github/mongoid/mongoid/Mongoid%2FContextual%2FMongo%3Afind_one_and_update

因此您的查询应该是:

next_number = TrackingId.where(id: id).find_one_and_update({
    :$inc => {
      auto_increment_counter: 1
    }
  },
  upsert: true,
  return_document: :after
).auto_increment_counter