2

I have a user.js file:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbName');

var User = mongoose.model('user', { username: String, password: String });

exports.User = User;

I am accessing the exposed User variable in other files.

However, I changed the file to this according to docs:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dbName');

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function callback () {
    console.log('connection open');
    var Schema = mongoose.Schema;

    var User = mongoose.model('user', { username: String, password: String });
    exports.User = User;
});

However, the User variable is undefine now in the other file.

Why is it so and how do I expose the User variable to other files?

1 Answer 1

3

I don't know which documentation you looked at, but I don't think that this is a good way to organise Mongoose schema. It would probably be better to define the schema in a separate file and then export that file. Here an example :

app.js :

var express = require('express');     
var app = express();

app.configure(function () {
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
});

var mongoose = require('mongoose');
mongoose.connect('mongodb:mongoURI');    

var db = mongoose.connection;
var userModel = require('../models/user.js');

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
    // Use userModel  ...
});

var userRoute = require('./routes/users');
app.get('/users/list', userRoute.list);

app.listen(3000);

models/user.js :

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

var userSchema = new Schema({
    id : ObjectId,
    name : {type : String, default : ''},
    email : {type : String, default : ''}
});

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

routes/users.js :

var user = require('../models/user.js');

exports.list = function(req, res) {
    user.find(function(err, users) {
        res.send(users);
    });
}; 
Sign up to request clarification or add additional context in comments.

2 Comments

I was looking at this: mongoosejs.com/docs/index.html. It says "let's assume that all following code is within this callback" and then defines the schema.
It is through an example to illustrate a concept, I do not think it advisable to do so in a real application.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.