我有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
变量公开给其他文件?
答案 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);
});
};