我尝试使用Bookshelf但遇到了未定义的模型错误。所以我尝试使用“注册表”插件,如中所述 bookshelf registry wiki。 我确实在这个github issue中提到了错误。但是只有一个对注册表插件的引用,并且该节点循环依赖管理问题可能导致它。我几乎完全复制了维基中的例子。
我的代码:
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
我在这里做错了什么?我错过了一些吗? (我对节点环境还不熟悉)
答案 0 :(得分:2)
该问题与注册表插件无关。无论如何,它的使用允许您将require()
移除到user.js
和todo.js
上的相关模型。
该修复只是在new
之前添加Todo
,因为您只能save()
一个实例:
new Todo({
description: "Walk the dogs",
user_id: 1,
completed: false
}).save().then(function(todo) {
console.dir(todo)
})