javascript - Bookshelf registry plugin and node cirrcular dependency errors -
i tried use bookshelf got stuck undefined models errors. tried use "registry" plugin described in bookshelf registry wiki. actualy got error mentioned in github issue. there reference registry plugin , node circular dependency managment issuesmay cause it. tied replicate example in wiki.
my code:
db.js
var client = require("knex"); var knex = client({ client: 'pg', connection: { host: '127.0.0.1', user: 'postgres', password: 'postgres', database: 'hapi-todo' }, pool: { min: 2, max: 10 }, debug: true }); var bookshelf = require('bookshelf')(knex); bookshelf.plugin('registry'); module.exports = bookshelf;
user.js
var db = require("../models/db"); require("../todos/todo"); var user = db.model.extend({ tablename: "users", todos: function () { return this.hasmany('todo', "user_id"); } }); module.exports = db.model("user", user);
todo.js
var db = require("../models/db"); require("../users/user"); var todo = db.model.extend({ tablename: "todos", user: function () { return this.belongsto('user'); } }); module.exports = db.model("todo", todo);
sample.js - works
var todo = require("./todos/todo") todo.collection().fetch().then(function(result) { console.log(result); });
this code runs expected , produces desired results.
sample.js
var todo = require("./todos/todo") todo({ description: "walk dogs", user_id: 1, completed: false }).save() .then(function(todo) { console.log(todo) })
this results in:
/node_modules/bookshelf/lib/base/model.js:57 this.attributes = object.create(null); ^ typeerror: cannot set property 'attributes' of undefined @ modelbase (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/base/model.js:57:19) @ child (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/extend.js:15:12) @ child (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/extend.js:15:12) @ child (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/extend.js:15:12) @ object.<anonymous> (/home/ubuntu/hapi-first/sample.js:3:1) @ module._compile (module.js:413:34) @ object.module._extensions..js (module.js:422:10) @ module.load (module.js:357:32) @ function.module._load (module.js:314:12) @ function.module.runmain (module.js:447:10) @ startup (node.js:141:18) @ node.js:933:3
what doing wrong here? missing somethig? (i new node environment)
the problem not related registry plugin. anyway use allow remove require()
related models on user.js
, todo.js
.
the fix adding new
before todo
, because can save()
instance:
new todo({ description: "walk dogs", user_id: 1, completed: false }).save().then(function(todo) { console.dir(todo) })
Comments
Post a Comment