user105813
user105813

Reputation: 17497

Seed embedded documents to MongoDB using Rails rake db:seed

How should db.seeds be structured in order to provide data for MongoDB, especially when containing embedded documents?

I ran into the following error when trying to seed a supposedly wrongly structured db.seeds file :

Cannot serialize an object of class ClassName into BSON.

Upvotes: 0

Views: 1455

Answers (2)

Scott
Scott

Reputation: 330

Start by creating a 'new' nested object like address, with attribute street and city, and setting it equal to a variable. Then create the parent object, in this case user with an attribute address, and assign the variable you created above to it. Since it is a nested object, you need to wrap your variable in an array []. Doing it this way will make it easy to read especially if you have a lot of nested objects. When referencing the nested object make sure to exclude any spaces after the colon or you will get an error.

a = Address.new(street: 'Any_Street', city: 'Any_City')
User.create(address:[a])

This will seed mongoDB with an address object which is nested in the user object.

Upvotes: 1

user105813
user105813

Reputation: 17497

Parent.create(title: 'foo', children: [
  Child.create(title: 'bar', date: Time.utc(2011,10,13)),
  Child.create(...),
  Child.create(...)
])

Upvotes: 0

Related Questions