Import json file into collection into server code at startup

I exported the MongodB collection to a JSON file on my local test computer and want to import it using the server side code of Meteor.js at startup (after deployment to meteor.com). I have not yet found examples of this.

thank

+4
source share
2 answers

Example:

    // import data only when Products collection is empty

    if (Products.find().count() === 0) {
        console.log("Importing private/products.json to db")

        var data = JSON.parse(Assets.getText("products.json"));

        data.forEach(function (item, index, array) {
            Products.insert(item);
        })
    }
+11
source

If your product set is small, you can get it all in one file and remove the parsing.

var products = [{/* product 1 */}, {/* product 2 */), ...];

if (Products.find().count() === 0) {
  products.forEach(function (product) {
    Products.insert(product);
  });
}

OR

With the new import in Meteor 1.3, you can import them instead, for example.

// fixtures/products.js

export default [{/* product 1 */}, {/* product 2 */), ...];

// fixtures/seed.js

import products from './products.js';

if (Products.find().count() === 0) {
  products.forEach(function (product) {
    Products.insert(product);
  });
}
0
source

All Articles