16

我是 node.js 的新手,我在访问声明多个猫鼬模式时遇到问题。

//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。

4

1 回答 1

39

当从单个文件中导出多个模型时,例如在 schema.js 中,您需要为每个导出的模型提供自己的exports字段名称。

例如,将module.exports = ...schema.js 中的多行替换为导出所有模型的文件末尾的以下代码:

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

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

var models = require('./schema');
...
models.User.findOne(...
于 2012-12-14T03:50:51.357 回答