Mongoid 中的原子持久性与推送

发布于 2024-11-05 08:11:39 字数 1384 浏览 0 评论 0原文

我不明白Mongoid的原子方法推送。

我有这个文档:

class Campaign
  include Mongoid::Document

  field :messages, :type => Array # Array of hashes
end

现在在控制台中可以使用它,但消息它没有持久化。一个例子:

>> campaign = Campaign.last
=> #<Campaign _id: 4dc2b6617e296d53f000000d,...
>> data = {:from => '[email protected]'}
=> {:from=>"[email protected]"}
>> campaign.push(:messages, data)
=> [{:from=>"[email protected]"}]

日志现在说:

MONGODB blabla_development['campaigns'].update({"_id"=>BSON::ObjectId('4dc2b6617e296d53f000000d')}, {"$push"=>{:messages=>{:from=>"[email protected]"}}})

但是如果再次查询这个文档,消息字段为nil:

>> campaign = Campaign.last
=> #<Campaign _id: 4dc2b6617e296d53f000000d,...
>> campaign.messages
=> nil

我怎样才能持久化这个数据?

谢谢

I don't understand the atomic method push of Mongoid.

I have this document:

class Campaign
  include Mongoid::Document

  field :messages, :type => Array # Array of hashes
end

And now in the console a play with it but messages it's not persisted. An example:

>> campaign = Campaign.last
=> #<Campaign _id: 4dc2b6617e296d53f000000d,...
>> data = {:from => '[email protected]'}
=> {:from=>"[email protected]"}
>> campaign.push(:messages, data)
=> [{:from=>"[email protected]"}]

The log now says:

MONGODB blabla_development['campaigns'].update({"_id"=>BSON::ObjectId('4dc2b6617e296d53f000000d')}, {"$push"=>{:messages=>{:from=>"[email protected]"}}})

But if a query this document again, the messages field is nil:

>> campaign = Campaign.last
=> #<Campaign _id: 4dc2b6617e296d53f000000d,...
>> campaign.messages
=> nil

How can I persist this data?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

楠木可依 2024-11-12 08:11:39

您推送的不是数组,而是哈希。启用安全模式 mongoid (mongomapper) 如果您希望 mongodb 回答“成功”或“失败”,请改为“好吧,无论如何”。

要启用安全模式,请尝试此操作

campaign.safe_mode?(:safe => true) #then carry on. warning, I haven't tested... 

push(... ,:safe => true) #mongomapper

或更改 config

persist_in_safe_mode true 

在任何情况下在开发环境中都应为 true 。

要解决您的问题:

#to use array instead of hash, do 
data = ["elem1", "elem2"]
#or
campaign.messages << "elem1"
campaign.messages << "elem2"
campaign.save!

You are not pushing an array, but a hash. Enable safe mode mongoid (mongomapper) if you want mongodb to answer "successful" or "failed", instead of "ok, whatever".

to enable safe mode, try this

campaign.safe_mode?(:safe => true) #then carry on. warning, I haven't tested... 

push(... ,:safe => true) #mongomapper

or change config

persist_in_safe_mode true 

should be true in development environment in any case.

To fix your problem:

#to use array instead of hash, do 
data = ["elem1", "elem2"]
#or
campaign.messages << "elem1"
campaign.messages << "elem2"
campaign.save!
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文