seanemmer / mongoose-seed

Seed data population for Mongoose
MIT License
52 stars 33 forks source link

How to Dynamically Reference in a Seeder an Object Id of a Document? #28

Open superKalo opened 6 years ago

superKalo commented 6 years ago

I have a seeder that seeds my States:

const states = {
  model: 'State',
  documents: [
    { name: 'Alabama', abbr: 'AL' },
    { name: 'Alaska', abbr: 'AK' },
    { name: 'Arizona', abbr: 'AZ' },
  ],
};

After the States seeder is done, each document gets Object ID by Mongo.

Then, I have another seeder, Survey. I want to reference the Object ID of one of the states inside it:

const surveys = {
  model: 'Survey',
  documents: [{
    user: 'superkalo@devlabs.bg',
    state: '<Object ID>' // Object ID of the 'Alabama' document?
  }],
};

Any ideas how to reference any State Object IDs in the Survey seeder?

I want to reference it somehow dynamic, because each time the States seeder executes, documents get different Object ID.

seanemmer commented 6 years ago

Would this solution work:

Have the populateModels return a promise that resolves with an array of the models that are created.

You can then chain populateModels calls and pass the results of a previous populateModels call to a subsequent one.

superKalo commented 6 years ago

I'm not really sure I understood your idea. How this will solve the issue that each time the seeder executes, documents get different Object ID?

Can you please share a code example?

mikevercoelen commented 6 years ago

@superKalo @seanemmer For exactly this reason I've created colonize, it has been used in production for a while now: https://www.npmjs.com/package/colonize

victorteokw commented 5 years ago

Hi @superKalo @seanemmer @mikevercoelen , Seedgoose supports fully dynamic smart id references. And we don't need to write seeding scripts. Writing data files is enough.

kimenyikevin commented 3 years ago

@superKalo I would suggest using the hardcoded id for reference of on object.