Nodejs在分离的文件上使用变量

时间:2016-11-19 07:50:15

标签: javascript node.js

我正在尝试在nodejs上使用和实现caminteJs,我创建了models文件夹,并且我有一些数据库模式包含在单独的文件中

user.js //contains user table schema
news.js //contains news table schema

进入index.js进入models文件夹,我有:

var users = require( './user' );
var news = require( './news' );

module.exports = {
    users:users,
    news:news
};

user.js文件内容:

var schema = require('../config');
module.exports = function(schema){
    var users = schema.define('channels', {
         user_name: { type: schema.String, limit: 30 },
         ...
         created_at: { type: schema.Date },
         updated_at: { type: schema.Date }
    });

    return users;
};

config.js文件内容:

var caminte = require( 'caminte' ),
    Schema = caminte.Schema,
    config = {
        driver: "mysql",
        host: "localhost",
        port: "3306",
        username: "root",
        password: "",
        database: "test",
        pool: true
    },
    schema = new Schema( config.driver, config );

module.exports = {
    caminte: caminte,
    Schema: Schema,
    config: config,
    schema: schema
}

然后我的server.js使用它们:

var socket = require( 'socket.io' ),
    ...
    config = require( './config' ),
    models = require( './models' );

server.listen( port, function () {
    console.log( 'Server listening at port %d', port );
} );

io.on( 'connection', function (socket) {
    socket.on( "new_channel", function (data, device) {
        new models.channels( { channel_name: 'Peter' } );
        console.log( channel );
    } );
} );

我在user.js上收到此错误:

TypeError: schema.define is not a function

1 个答案:

答案 0 :(得分:0)

可能应该是:

var users = schema.schema.define('channels', {

因为你在这里定义了:

module.exports = {
    caminte: caminte,
    Schema: Schema,
    config: config,
    schema: schema // <- this
}

schema中的user.js与您在module.exports中定义的对象相同。

您可以重写user.js

var config = require('../config');
module.exports = function(schema){
    var users = config.schema.define('channels', {
         user_name: { type: config.schema.String, limit: 30 },
         ...
         created_at: { type: config.schema.Date },
         updated_at: { type: config.schema.Date }
    });

    return users;
};