在db.open()回调中使用导出 - mongoose / express

时间:2014-01-19 13:23:35

标签: javascript node.js mongodb express mongoose

我有user.js个文件:

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

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

exports.User = User;

我正在访问其他文件中公开的User变量。

但是,我根据文档更改了文件:

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

但是,User变量现在在另一个文件中取消定义。

为什么会如此?如何将User变量公开给其他文件?

1 个答案:

答案 0 :(得分:3)

我不知道您查看了哪些文档,但我认为这不是组织Mongoose架构的好方法。最好在单独的文件中定义模式,然后导出该文件。这是一个例子:

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