gpt4 book ai didi

javascript - 书架注册表插件和 Node 循环依赖错误

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:52 25 4
gpt4 key购买 nike

我尝试使用 Bookshelf,但遇到了未定义模型错误。所以我尝试使用中描述的“注册表”插件 bookshelf registry wiki .我实际上遇到了此 github issue 中提到的错误.但是只有对注册表插件的引用, Node 循环依赖管理问题可能会导致它。我几乎完全复制了 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;

用户.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);

待办事项

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);
});

此代码按预期运行并产生预期结果。

示例.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

我在这里做错了什么?我错过了什么吗?(我对 Node 环境还很陌生)

最佳答案

问题与注册表插件无关。无论如何,它的使用允许您删除 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)
})

关于javascript - 书架注册表插件和 Node 循环依赖错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36727399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com