书架 js save() 命令不更新 postgresql db 中的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31389157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:58:10  来源:igfitidea点击:

bookshelf js save() command not updating rows in postgresql db

postgresqlbookshelf.js

提问by David Upsdale

JS beginner trying to get a PostgreSQL DB talking to express.js through bookshelf.js.

JS 初学者试图通过 bookshelf.js 获得与 express.js 对话的 PostgreSQL DB。

github: https://github.com/duskyshelf/bookers-academy/blob/master/booker.js

github:https: //github.com/duskyshelf/bookers-academy/blob/master/booker.js

var knex = require('knex')({
  client: 'pg',
  connection: "postgres://localhost/bookers"
});

var bookshelf = require('bookshelf')(knex);

var User = bookshelf.Model.extend({
  tableName: 'users'
});

var bob = new User({id: 2});
bob.save()

bookshelf.js seems unable to add any content to the db.

bookshelf.js 似乎无法向数据库添加任何内容。

Current error message is: "Unhandled rejection CustomError: No Rows Updated'

当前的错误消息是:“未处理的拒绝 CustomError: No Rows Updated”

回答by flaviodesousa

When you create your model providing your own id, like in

当您创建提供您自己的 id 的模型时,例如

var bob = new User({id: 2});

Bookshelf assumes it is an updateoperation, notan insertion. It sets the internal isNewattribute to false, and when save()is invoked, instead of INSERT INTO user(id, ...) VALUES (2, ...);, it executes UPDATE user ... WHERE id = 2;.

Bookshelf 假定它是更新操作,而不是插入操作。它将内部isNew属性设置为 false,并在save()被调用INSERT INTO user(id, ...) VALUES (2, ...);时执行,而不是UPDATE user ... WHERE id = 2;

If there is no user with id = 2the update will almostsilently DO NOTHING.

如果没有用户id = 2的更新将几乎悄无声息无能为力

To force an insert you must change the save() to:

要强制插入,您必须将 save() 更改为:

bob.save(null, {method: 'insert'});

Bookshelf save() documentationdescribes this behavior.

Bookshelf save()文档描述了这种行为。

回答by medhir

Did you create a User table using knex? One potential problem I can think of is that you do not have any logic that actually creates the table for your Postgres DB. Here is some sample code that will create a table in your database if it doesn't yet exist.

您是否使用 knex 创建了用户表?我能想到的一个潜在问题是,您没有任何实际为 Postgres 数据库创建表的逻辑。下面是一些示例代码,如果它尚不存在,它将在您的数据库中创建一个表。

bookshelf.knex.schema.hasTable('User').then(function(exists) {
  if(!exists) {
    bookshelf.knex.schema.createTable('User'), function(user) {
      user.increments('id').primary();
      user.timestamps();
    }).then(function(table){
      console.log('Created Table:', table);
    });
  }
});

回答by n00b

new User({id: 2}).
 save().
 then((model) => {
  res.json({ success: true });
});

回答by uglycode

No no! new User returns a PROMISE! You can't use it like that. Try

不,不!新用户返回一个承诺!你不能那样使用它。尝试

new User().save()