mongoose-seed icon indicating copy to clipboard operation
mongoose-seed copied to clipboard

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

Open superKalo opened this issue 7 years ago • 5 comments
trafficstars

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: '[email protected]',
    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.

superKalo avatar Jul 04 '18 15:07 superKalo

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.

seanemmer avatar Jul 30 '18 17:07 seanemmer

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?

superKalo avatar Jul 31 '18 08:07 superKalo

@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

mikevercoelen avatar Aug 06 '18 04:08 mikevercoelen

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.

victorteokw avatar May 07 '19 01:05 victorteokw

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

kimenyikevin avatar Dec 27 '20 06:12 kimenyikevin