wazzaday
wazzaday

Reputation: 9664

Importing the contents of a folder with Meteor

I have a folder containing individual files for different Mongo Collections. I want to read the contents of the directory and dynamically create each collection in meteor. Kind of like:

let collections = {}; 
let fs = Npm.require('fs');
let files = fs.readDirSync('path-to-my-folder');
files.forEach(fileName, () => {
    let schema = Npm.require('path-to-my-folder/'+fileName);
    let collection = new Mongo.Collection(fileName);
    collections[fileName] = collection; //store collection

    // Create method, and publications for each collection
});

// export function to get any collection by name
export default function(name){
    return collections[name];
}

The issue here is that when I load the site I get the error Npm is not defined

I understand that this is because Npm is only available server side. But I need these collections to be available on the client as well. Is this kind of a thing possible with Meteor?

Upvotes: 1

Views: 170

Answers (1)

corvid
corvid

Reputation: 11187

If you're using Meteor on the server with 1.3, you probably want something like this:

import { Mongo } from 'meteor/mongo';
import { readDirSync } from 'fs';

export let collections = {};

readDirSync('some-dir/').forEach(file => {
  const schema = require(`./${file}`);
  const collection = new Mongo.Collection(file);
  collections[file] = collection;
})

export default function getCollection(name) {
  return collections[name];
}

Upvotes: 2

Related Questions