Bookshelf注册表插件和节点循环依赖性错误

Bookshelf registry plugin and node cirrcular dependency errors

本文关键字:循环 依赖性 错误 节点 注册表 插件 Bookshelf      更新时间:2023-09-26

我尝试使用Bookshelf,但遇到了未定义的模型错误。因此,我尝试使用"注册表"插件,如中所述书架注册wiki。事实上,我在这个github问题中提到了错误。但这里只提到了注册表插件,节点循环依赖关系管理问题可能会导致这种情况。我在wiki中几乎完全复制了这个例子。

我的代码:

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

我在这里做错了什么?我是不是错过了什么?(我对节点环境相当陌生)

问题与注册表插件无关。无论如何,它的使用允许您将require()删除到user.jstodo.js上的相关模型。

修复方法只是在Todo之前添加一个new,因为您只能save()一个实例:

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