mongoose + express + mongodb声明多个模式后不能从数据库获取数据

我是新来的node.js和我有问题时访问多个mongoose模式声明。

模型中的//schema.js

var mongoose = require('mongoose'); var Schema = mongoose.Schema , ObjectId = Schema.ObjectId; //User Schema var userSchema = new Schema({ id: ObjectId, firstname: {type: String, require: true}, lastname: {type: String, require: true}, username: {type: String, unique: true, require: true}, password: {type: String, require: true}, role: {type: [String], require: true} }) var User = mongoose.model('User', userSchema); module.exports = User; //Question Schema var qnSchema = new Schema({ id: ObjectId, question: {type: String, require: true}, module_id: {type: ObjectId, ref: 'Module'} }) var Question = mongoose.model('Question', qnSchema); module.exports = Question; //Answer Schema var ansSchema = new Schema({ id: ObjectId, answer: String, question: {type: ObjectId, ref: 'Question'} }) var Answer = mongoose.model('Answer', ansSchema); module.exports = Answer; //Module Schema var modSchema = new Schema({ id: ObjectId, name: {type: String, require: true} }) var Module = mongoose.model('Module', modSchema); module.exports = Module; //Role Schema var roleSchema = new Schema({ id: ObjectId, role: {type: String, require: true} }) var Role = mongoose.model('Role', roleSchema); module.exports = Role; 

控制器中的//index.js

 var mongoose = require('mongoose'); var User = require('../models/schema'); var db = mongoose.connect('mongodb://localhost/damai'); module.exports = function(app) { app.get('/', function(req, res) { if (typeof req.session.userid == 'undefined') { res.render('login', { title: app.get('title') }); } else { res.render('index', { title: app.get('title') }); } }); app.post('/login', function(req, res) { passwordVerification(req, res); }); } function passwordVerification(req, res) { var userid = req.param('userid'); var password = req.param('password'); User.findOne({'username': userid},{'password': 1}, function(err, cb) { console.log(cb); if(cb!= null) { if (password == cb.password) { req.session.userid = userid; res.render('index', { title: app.get('title'), 'userid': userid }); } else { res.render('login', { title: app.get('title'), error: 'Invalid login'}); } } else { res.render('login', { title: app.get('title'), error: 'Invalid login'}); } }); } 

当我在schema.js中只有“用户模式”时,从index.js中调用方法“passwordVerification()”的数据库将返回从数据库中检索到的相关密码。 但是,当我开始在schema.js中添加其他模式(如“问题模式”)时,方法“passwordVerification()”将始终返回null。

       

网上收集的解决方案 "mongoose + express + mongodb声明多个模式后不能从数据库获取数据"

当从类似于您的单个文件中导出多个模型在schema.js中时,您需要为每个导出的模型指定自己的exports字段名称。

例如,将以下代码replacemodule.exports = ...的multiple module.exports = ...行,以便导出所有模型:

 module.exports = { User: User, Question: Question, Answer: Answer, Module: Module, Role: Role }; 

然后在index.js中,你可以像这样访问模型:

 var models = require('./schema'); ... models.User.findOne(...