Ethan Turkeltaub
Ethan Turkeltaub

Reputation: 2961

Get EmbeddedDocument's Parent Document's ID in MongoMapper

Suppose the following model.

class Person
  include MongoMapper::Document

  key :name, String
  key :surname, String

  many :children
end

class Child
  include MongoMapper::EmbeddedDocument

  key :name, String
end

Plus, the following query (with Sinatra):

get 'child/:id' do
  @child = Child.find(params[:id])
end

Is there a way to get the ID of the Person that that Child belongs to?

Upvotes: 2

Views: 673

Answers (1)

Ariel Backenroth
Ariel Backenroth

Reputation: 36

I think what you're looking for is this:

class Child
  include MongoMapper::EmbeddedDocument

  embedded_in :parent
  key :name, String
end

I'm not quite sure how your query works - I'm not seeing that there's a find on the Child class since it's an EmbeddedDocument. However:

Person.where("children._id" => params[:id]).first.parent

should work.

Upvotes: 2

Related Questions