Brinka
Brinka

Reputation: 89

mongoose schema is broken into several files, how to require?

doing mongoose db in nodejs. i got an error: "schema is not defined".

in my model i have 2 files for different schemas: user and product, they look smth like:

'use strict';
var mongoose = require('mongoose'),
    bcrypt = require("bcryptjs");

var UsersSchema = new Schema({
  name: String,
  email: String,
  telephone: Number,
  createdAt: {type: Date, default: Date.now},
  updatedAt: {type: Date, default: Date.now}
});


var userModel = mongoose.model('User', userSchema);
module.exports.userModel = userModel;

I have nothing in routes, and in app.js, I've got:

var users = mongoose.model('User', userSchema);
var products = mongoose.model('Product', productSchema);

Previously I tried:

 var users = require('../models/userSchema');
 var products= require('../models/productSchema');

any advise? thanks

Upvotes: 1

Views: 891

Answers (2)

Talha Awan
Talha Awan

Reputation: 4619

You can get rid of requiring mongoose models in your code by putting them in app.

Add index.js file in the folder (let's say 'models') where user.js and product.js are placed:

var fs                = require('fs');
var path              = require('path');
module.exports = function(app) {
    app.models = app.models || {};
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file !== "index.js" && path.extname(file) === '.js'){
            var model = require(path.join(__dirname,file))(app);
            app.models[model.modelName] = model;

        }
    });
};

Change user.js (and similarly product.js) file to

'use strict';
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    bcrypt = require("bcryptjs");
module.exports = function(){
    var UsersSchema = new Schema({
        name: String,
        email: String,
        telephone: Number,
        createdAt: {type: Date, default: Date.now},
        updatedAt: {type: Date, default: Date.now}
    });
    return mongoose.model("User", UsersSchema); //the name "User" here will be stored as key in app.models and its value will be the model itself
};

And in app.js insert a line

 require("./app/models")(app) //pass app to the index.js, which will add models to it

Now you can use app.models.User and app.models.Product across the application.

Upvotes: 0

qqilihq
qqilihq

Reputation: 11474

To resolve the "schema is not defined" issue, import the Mongoose schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

For the exports, I would suggest the following. No reason to nest this additionally, when you're defining one model per file:

var userModel = mongoose.model('User', userSchema);
module.exports = userModel;

Then you can require the model in other files as shown in your post, e.g.:

var users = require('../models/userSchema');

Upvotes: 2

Related Questions