How to change a document's _type in Mongoid?

喜欢而已 提交于 2019-12-10 04:19:28

问题


I have the following models inside a Rails application:

class User
  include Mongoid::Document
  ...
end

class Admin < User
  ...
end

I get a user:

u = User.find(some_key)

And try to change the _type:

u._type  # => "User"
u._type = "Admin"
u.save
u._type  # => "Admin"

But if I reload the object it's still a user:

u.reload
u._type = "User"

What is the correct way to change this?


回答1:


you could also use Model#update_attribute to stay with mongoid:

user.update_attribute(:_type, "Admin")



回答2:


Ended up solving it by using a raw MongoDB query:

users.update( { :"_id" => user.id }, { :"$set" => { :"_type" => "Admin" }})


来源:https://stackoverflow.com/questions/5306646/how-to-change-a-documents-type-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!