How do you check if an embedded document exists in a document in mongoid?

How do you check if an embedded document exists for a document using mongoid in Ruby on Rails? Let's say I have a user document that has name , email and can have an embedded nicknames document. Right now, if I run user.first.nicknames , and if this user does not have an embedded nicknames document, it will fail. Have I tried matches? and exists? but they do not work.

Thanks!

+6
source share
4 answers

Should this return true if it does not exist User.first.nicknames.nil? and this will return true if it exists: User.first.nicknames.present?

+3
source

With a little help from the other answers here, I found something that worked for me, and I think this is what the original poster had in mind;

 Model.where(:"subdoc.some_attribute".exists => true) 

This will return all documents where "some_attribute" exists in the subdocument. Pay attention to the syntax of the character, to what I was missing.

+8
source

You can do User.where(:nicknames.exists => true).include?(user) .

User.where(:nicknames.exists => true) will only return documents containing nicknames .

+2
source

should be as simple as {"user":{"$exists":"nicknames"}}

0
source

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


All Articles