Processing Node.js Async Returns with a Request (Node ORM)

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.

+4
source share
3 answers

Perhaps, can make person.js export to a function and pass to db? Like this:

 //app.js var orm = require("orm"); var db = orm.connect("creds", function (success, db) { if (!success) { console.log("Could not connect to database!"); return; } var Person = require("./models/person.js")(db); }); //person.js module.exports = function(db){ return db.define("person", { "name" : { "type": "string" }, "surname": { "type": "string", "default": "" }, "age" : { "type": "int" } }); } 
+7
source

If you put the code that you placed here in a function, you can export it and use it in person.js (or vice versa)

+1
source

Node -orm is not so good. The Node-mysql driver has a built-in implementation, but Node -orm does not. You can use light-orm as a wrapper for Node-mysql. You will get truly flexible models.

https://npmjs.org/package/light-orm and https://npmjs.org/package/mysql

+1
source

Source: https://habr.com/ru/post/1413355/


All Articles