James
James

Reputation: 57

Import json file into collection in server code on startup

I've exported a MongodB collection to a JSON file on my local test machine and want to import it through the Meteor.js server side code on startup (after deploying to a meteor.com site). I'm not finding any examples of this yet.

Thanks

Upvotes: 4

Views: 2923

Answers (2)

Merlin -they-them-
Merlin -they-them-

Reputation: 2960

If your set of products is small, you could have it all in the same 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 imports in Meteor 1.3, you could import them instead, like so.

// 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);
  });
}

Upvotes: 0

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

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);
        })
    }

Upvotes: 11

Related Questions