Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

I need help converting a file into a reusable module in node.

I am using the following file to seed a mongodb database. This file runs exactly as it should and returns exactly the result I am expecting, when I execute it as a standalone file. My issue is I want to use this file in two different places in my app. So I am trying to make it an exportable/importable module. Here is what I have tried:

seed.js looks like this:

'use strict';

//  library modules
const {ObjectID} = require('mongodb');
const seeder     = require('mongoose-seed');    //  NOTE: rejected "mongoose-seeder" because it seems to be out of sync with mongodb
const jwt        = require('jsonwebtoken');
const util       = require('util');

//  local modules
const {Course}   = require('./../models/course');
const {Review}   = require('./../models/review');
const {User}     = require('./../models/user');
const {data}     = require('./../data/data.js');
const config     = require('./../config/config.js');

/*==================================================
    build seeding Courses, Reviews, Users
==================================================*/

// Connect to MongoDB via Mongoose
let seed = seeder.connect(process.env.MONGODB_URI, (e) => {
    console.log(`Connected to: ${process.env.MONGODB_URI} and seeding files`);

    // Load Mongoose models
    seeder.loadModels([
        'src/models/user.js',
        'src/models/review.js',
        'src/models/course.js'
    ]);

    // Clear specified collections
    seeder.clearModels(['User', 'Review', 'Course'], function() {

        // Callback to populate DB once collections have been cleared
            seeder.populateModels(data, function() {
            seeder.disconnect();
        });

    });
});

module.exports = seed;

Within app.js I have these two lines

const seed         = require('./middleware/seed');

and

app.use(seed);

I have also tried, to no avail

app.use(seed());

What is missing? I don't want to use the code in line in two different places (DRY you know).

It is failing with "throw new TypeError('app.use() requires a middleware function')"

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Out of curiosity, what happens when you try module.exports.seed = seed; ? I feel like the problem might lie in the exporting of the module.

1 Answer

OK, for those interested, here is the solution. My seed.js file needed to be modified as follows:

/*==================================================
    build seeding Courses, Reviews, Users
==================================================*/

// declare seeding
function seedDB(next) {
    seeder.connect(process.env.MONGODB_URI, (e) => {
        console.log(`Connected to: ${process.env.MONGODB_URI} and seeding files`);

        // Load Mongoose models
        seeder.loadModels([
            'src/models/user.js',
            'src/models/review.js',
            'src/models/course.js'
        ]);

        // Clear specified collections
        seeder.clearModels(['User', 'Review', 'Course'], function() {

            // Callback to populate DB once collections have been cleared
                seeder.populateModels(data, function() {
                seeder.disconnect();
            });

        });
    });
}

//  execute seeding
seedDB();

const seed = (req, res, next) => {
    seedDB(next());
};

module.exports = seed;

middleware must always be a function with a next(), mine wasn't.