I am using the ORM Node.js module: https://github.com/dresende/node-orm
I can create a model by following these steps:
var orm = require("orm"); var db = orm.connect("creds", function (success, db) { if (!success) { console.log("Could not connect to database!"); return; } var Person = db.define("person", { "name" : { "type": "string" }, "surname": { "type": "string", "default": "" }, "age" : { "type": "int" } }); });
The problem is that I want to put Person (and all other models, for that matter) into external ones.
If I do something like this:
require("./models/person.js");
I cannot use the db variable inside this because it exists only in the context of the callback function for orm.connect (). I can not move orm.connect to require (person.js) and make module.export for the model information, because in the parent script this will happen, and then the model will not be ready for the next line, since it does not wait for an answer. IE
//person.js // db and orm get defined up here as before Person = {}; // code from above, with the define and etc. Module.exports = Person; //app.js person = require("./models/person.js"); console.log(person); // returns undefined, connect callback isn't done yet
I feel that there is an obvious way to do this.
source share