Delete field in document in mongodb - Rails + Mongoid

I want to delete a field in a document using ROR.

I have already tried

  • book.remove_attribute (: name)
  • book.unset (: name)

But both of them set the attribute to nil, and it is still present in the object.

I want it to disappear from my document. Any help is appreciated.

+5
source share
1 answer

When you access a document through mongoid, it returns you a Ruby object. In fact, you can see the data stored in the document only through the mongo shell (just enter "mongo" into your terminal).

The object is created by Mongoid (MongoDB ODM / wrapper for rails). This object may sometimes differ from the document.

for instance

When you disable a field, this field is completely removed from this document. BUT, since your model still has this field, MONGOID returns you the nil attribute for this field, instead of giving you a different number of fields for objects of the same model.

Model book.rb

class Book include Mongoid::Document field :name field :author end 

In the rails console, type

  Book.create(name: "b1", author: "a1") => #<Book _id: 555231746c617a1c99030000, name: "b1", author: "a1"> 

In Mongo shell

 db.books.find() { "_id" : ObjectId("555231746c617a1c99030000"), "name" : "b1", "author" : "a1" } 

Now we are not sure.

In rails console

 Book.first.unset(:name) => #<Book _id: 555231746c617a1c99030000, name: nil, author: "a1"> 

In Mongo shell

 db.books.find() { "_id" : ObjectId("555231746c617a1c99030000"), "author" : "a1" } 

If you still do not want to see the field in the rails console (remember that this does not take up extra space in db), you can always remove the field from the model. If you do this, you will no longer be able to access this field through rails / mongoid on any object. It will be present only in the document and is accessible through the mongo shell.

+4
source

All Articles