Reputation: 3105
How do you check if an embedded document exists for a document using mongoid in Ruby on Rails? Say I have a document user
that has name
, email
, and might have a nicknames
embedded document. Right now if I run user.first.nicknames
and if that user
doesn't have the nicknames
embedded document in it, it will error out. I've tried matches?
and exists?
but they don't work.
Thanks!
Upvotes: 7
Views: 5401
Reputation: 2460
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 the "some_attribute" exists on the subdocument. Notice the syntax of the symbol, that's what I was missing.
Upvotes: 14
Reputation: 319
You can do User.where(:nicknames.exists => true).include?(user)
.
User.where(:nicknames.exists => true)
will return only the documents which contain nicknames
.
Upvotes: 2
Reputation: 28574
This should return true if it doesn't exist User.first.nicknames.nil?
and this will return true if it does exist: User.first.nicknames.present?
Upvotes: 3