Nodejs undefined var 在模型中分离代码时

Nodejs undefined var when separate code in models

我正在编写我的第一个 nodejs 应用程序,当我将一段代码移动到外部 js 文件时出现错误。我要移动的代码是 mongodb 模式声明:

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

//--------------------users ------------
var usersSchema = new Schema({
    email: String,
    name: String, 
    phoneNumber: String, 
    BirthDate: Date, 
    loginpwd:String
});

var UserModel = mongoose.model('users', usersSchema);

我正在使用文件系统模块加载外部文件:

fs.readdirSync(__dirname+'/models').forEach(function(filename){
    if (~filename.indexOf('.js')) 
        require(__dirname+'/models/'+ filename);
    console.log(filename+" added");
});

当我分离代码时,以下块无法正常工作,抛出 "undefined UserModel" 错误:

var userData = new UserModel({email : req.body.edtEmail,
                                        name: req.body.edtName,
                                        phoneNumber: req.body.edtPhoneNumber,
                                        BirthDate: req.body.edtBirthDate,
                                        loginpwd: req.body.edtSenha});
// save user data to database
userData.save(function(err, record){
   if(err) throw err;

    // session setting
    req.session.userEmail = req.body.edtEmail;
    req.session.name = req.body.edtName;
    req.session.phoneNumber = req.body.edtPhoneNumber;
    req.session.birthDate = req.body.edtBirthDate;
    req.session.userId = record._id;
    res.redirect('/dashboard');
});

以下代码在内联代码或 "in file" 代码中运行良好:

app.get('/users/json', function(req, res){
    mongoose.model('users').find(function(err, users){
        res.send(users);
    });
 });

加载外部文件时我做错了什么吗?或遗漏了什么?

nodeJs内置了加载文件的系统。

我不太确定你想做什么,但在 nodejs 中你会做这样的事情

//Lets say this file is called UserModel.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

//-------------------- rest of you code ------------


var UserModel = mongoose.model('users', usersSchema);
module.exports = UserModel; //this is important

比起在另一个文件中你可以只加载这个

var UserModel = require('UserModel'); 
var bob = new UserModel({ .... 

这样您就可以使用您的 UserModel。阅读有关 require

的文档

也可以这样使用:

在您的模式文件中:(比如目录“models/userModel.js”)

...
mongoose.model('UserModel', usersSchema);

在您要使用的控制器或其他文件中:(比如目录“controller/userController.js”)

require('../models/userModel');// load user model
var mongoose = require('mongoose'),
    UserModel = mongoose.model('UserModel'),

var userData = new UserModel({email : req.body.edtEmail, //rest of code...});

userData.save(function(err, record){ //rest of code ...

并且可以像这样用于路线:(像控制器一样跟随)

app.get('/users/json', function(req, res){
    UserModel.find(function(err, users){
        res.send(users);
    });
 });