tux-world tux-world - 16 days ago 5
Javascript Question

Nodejs using variables on separated files

i'm trying to use and implementing

caminteJs
on nodejs, i created
models
folder and in that i have some database schema which wrapped into separated file as

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


into
index.js
which its into
models
folder i have:

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

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


user.js
file content:

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
file content:

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
}


and then my
server.js
to use them:

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 );
} );
} );


I get this error on
user.js
:

TypeError: schema.define is not a function

Answer

Probably it should be:

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

Because you defined that here:

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

So schema in user.js is the same object you defined in the module.exports.

You could rewrite user.js as this:

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;
};
Comments