考虑这个例子:
> x = User.first # or any persisted Mongoid::Document
=> #<User _id: 52014532a6356d1ac9000001, ...>
> x.set :foo, :bar
=> :bar
> x.set :foo2, 'bar'
=> "bar"
请注意,“foo”和“foo2”没有在 Ruby 的任何地方声明。
然后,在 MongoDB shell 中:
> db.users.findOne({_id: ObjectId('52014532a6356d1ac9000001')})
{
"_id" : ObjectId("52014532a6356d1ac9000001"),
"foo" : "bar",
"foo2" : "bar",
...
}
但是现在,回到 Ruby:
> x = User.find x.id; nil # to clear out any possibility of metadata on the instance
=> nil
> [x.read_attribute(:foo), x.read_attribute(:foo2)]
=> [:bar, "bar"]
它是怎么知道的?