What is the best method to seeding a Node / MongoDB application?

前端 未结 4 1396
一个人的身影
一个人的身影 2021-02-05 11:15

So, I\'m new to the MEAN stack, and I\'ve hit a wall trying to seed MongoDB. I\'m using Mongoose to communicate with the database, and there\'s a bunch of documentation suggesti

4条回答
  •  攒了一身酷
    2021-02-05 11:47

    I solved this issue on a project by dumping the relevant data to an extended JSON array formatted file using mongoexport --jsonArray, then importing this back into POJO format inside the Node application using the EJSON package. I then just use Mongoose to insert the resulting JS array back into the database using the correct collection model you've created using Mongoose.

    The necessary JSON data files to seed the application for a first-run are checked into the application repository. Here's a quick sample you may be able to adapt to your purposes:

    // ...
    // 'Items' is the Mongoose collection model.
    const itemResult = await Items.find({}).exec();
    if(itemResult.length === 0) {
      const itemsSeedDataRaw = fs.readFileSync(`${__dirname}/data/items.json`, 'utf8');
      const itemsSeedData = EJSON.parse(itemsSeedDataRaw);
      await Items.insertMany(itemsSeedData);
    }
    // ...
    

提交回复
热议问题