2016-04-19 21 views
3

我試圖使用Bookshelf但卡住了未定義的模型錯誤。所以我嘗試使用 bookshelf registry wiki中描述的「註冊表」插件。 我真的得到了這個github issue中提到的錯誤。但是隻有對註冊表插件的引用以及節點循環依賴關係管理問題可能導致它。我幾乎完全複製了wiki中的例子。書架註冊表插件和節點cirrcular相關性錯誤

我的代碼:

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 - 工程

var Todo = require("./todos/todo") 

Todo.collection().fetch().then(function(result) { 
    console.log(result); 
}); 

此代碼按預期運行併產生所需的結果。

sample.js

var Todo = require("./todos/todo") 

Todo({ 
    description: "Walk the dogs", 
    user_id: 1, 
    completed: false 
}).save() 
.then(function(todo) { 
    console.log(todo) 
}) 

這導致:

/node_modules/bookshelf/lib/base/model.js:57 
    this.attributes = Object.create(null); 
       ^

TypeError: Cannot set property 'attributes' of undefined 
    at ModelBase (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/base/model.js:57:19) 
    at Child (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/extend.js:15:12) 
    at Child (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/extend.js:15:12) 
    at Child (/home/ubuntu/hapi-first/node_modules/bookshelf/lib/extend.js:15:12) 
    at Object.<anonymous> (/home/ubuntu/hapi-first/sample.js:3:1) 
    at Module._compile (module.js:413:34) 
    at Object.Module._extensions..js (module.js:422:10) 
    at Module.load (module.js:357:32) 
    at Function.Module._load (module.js:314:12) 
    at Function.Module.runMain (module.js:447:10) 
    at startup (node.js:141:18) 
    at node.js:933:3 

我在做什麼錯在這裏?我錯過了什麼? (我對節點環境相當陌生)

回答

2

問題與註冊表插件無關。無論如何,它的使用允許您刪除require()user.jstodo.js上的相關型號。

的修補程序簡單地增加一個前Todonew,因爲你只能save()一個實例:

new Todo({ 
    description: "Walk the dogs", 
    user_id: 1, 
    completed: false 
}).save().then(function(todo) { 
    console.dir(todo) 
}) 
+1

謝謝,我以爲我已經錯過了一些小事,在這裏我們去... –