Request inline documents for a document using MongoMapper

What is a good template for querying embedded documents in a document? For example, in my User document there is an embedded Alerts document. If I want to find out if a given user has a warning with a name, I can do this in two ways, as far as I can tell - in memory a la

alert = current_user.alerts.select{|a| a.name == params[:name]}.first

or through the a la document interface (note that I'm not 100% sure that this is semantically valid, but you get the point):

User.where('alerts.name' => params[:name], :id => current_user.id).first

There MUST be a better way, something like

current_user.alerts.where(:name => params[:name])

may be? Or maybe I'm just not thinking about the problem correctly?

+6
source share
3 answers

Nope. And I think this is motivation:

In MongoMapper, database queries always return the root object. Allowing requests to return an embedded document without its parent would be a violation with this and complicating many things (what if I call .parent inside this embedded document?), Therefore, MongoMappers are mistaken on the simplicity side and do not pretend that this is what they are not . Inline documents are stored in an array inside the root document in MongoDB, so MongoMapper provides you with an array in Ruby.

So, your two ways to do this are the intended ways to do this.

If you need a syntactic shuger, it shouldn't be too hard to code. You could extend Array or you could encode a plugin to extend MongoMapper proxy for embedded documents .

0
source

I think Mongoid supports this, see the "Search" in the manual for embedded documents .

0
source

You can do either:

 User.where('alerts.name' => params[:name], :id => current_user.id).fields(:alerts).first.alerts.select{|u| u.name == params[:name]} 

or

 User.where('alerts.name' => params[:name], :id => current_user.id).fields(:alerts).alerts.select{|u| u.name == params[:name]}.first 
-1
source

Source: https://habr.com/ru/post/889016/


All Articles