seed a json array

default discord avatar
generator101
8 months ago
22

I have a json array



[
  {
   "id" : 1,
   "name" : "john"
  },
  {
   "id" : 2,
   "name" : "bob"
  },
  ....
]


I want to seed all the data to a collection,


I loaded the json file



const data = require('../../data/data.json')


but not sure how to load all the individual data, any ideas?

  • default discord avatar
    notchr
    8 months ago

    @generator101 Do you mean mapping over your provided array to a payload collection config?

  • default discord avatar
    generator101
    8 months ago

    yes

  • default discord avatar
    notchr
    8 months ago

    It may be something like this



    Wait



    you mean import data into a collection already made?



    Or create a collection from a predefined config?

  • default discord avatar
    generator101
    8 months ago

    so I am using this example



    https://github.com/payloadcms/next-auth-cms/blob/main/src/collections/Users/seed.ts


    it is seeding 1 user, I want to seed multiple users



    that are in a json format in a file data.json



    the collection I already made



    with proper fields

  • default discord avatar
    notchr
    8 months ago

    Oh okay



    So you could do a few things, but maybe you want to loop over your provided users data json



    USERS_JSON.forEach((user) => {
        await payload.create({
          collection: 'users',
          data: {
            ...user,
          },
        });
    })


    Assuming your data in users_json is compatible with the users collection model



    Note: To hook into when all users are created, you may want to create an array of those .create methods and then Promise.all it



    @jmikrut may have a better way. Maybe a PR for createMany would be cool?

  • default discord avatar
    generator101
    8 months ago

    Thank you, this worked, but createMany would be awesome

  • discord user avatar
    jmikrut
    Payload Team
    8 months ago

    we are working on

    createMany

    😉

  • default discord avatar
    mumincelal
    4 months ago

    What about if we want to insert USERS_JSON file with multi-language support?



    USERS_JSON.forEach((user) => {
        await payload.create({
          collection: 'users',
          data: {
            ...user,
          },
          locale: 'es'
        });
    })


    this code creates another document instead of updating previous one.



    @jmikrut and @notchr

  • discord user avatar
    jmikrut
    Payload Team
    4 months ago

    @mumincelal



    you would want to use

    payload.update

    instead of

    payload.create
Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.