【问题标题】:Bookshelf - get the id when a new record is createdBookshelf - 创建新记录时获取 id
【发布时间】:2020-05-28 19:08:47
【问题描述】:

我在我的项目中使用带有 mysql 的书架,但在创建新记录时无法弄清楚如何获取 id。相反,它只是返回 undefined。

// model.js
const User = bookshelf.model('User', {
  tableName: 'user',
  hidden: ['password']
});

// main.js
User.forge(attributes)
    .save()
    .then(function (newRow) {
      console.log(newRow.id); // Should return the id
    })
    .catch(function (err) {
      // Handle errors
    });

【问题讨论】:

    标签: javascript node.js knex.js bookshelf.js


    【解决方案1】:

    newRow 对象仅包含来自 attributes 的字段。要获取行 ID,我们需要从数据库中读取这一行。

    可能这是一个拐杖,但我不知道更好的解决方案。

    const User = bookshelf.model('User', {
      tableName: 'user',
      hidden: ['password']
    });
    
    // main.js
    User.forge(attributes)
        .save()
        .then(function (newRow) {
          console.log(newRow.id); // undefined
          User.where(attributes).fetch()
            .then((createdUser) => {
              console.log(createdUser); // any id (1 for example)
            })
            .catch(function (err) {
              // Handle errors
            });
        })
        .catch(function (err) {
          // Handle errors
        });

    P.S 最好使用 javascript async/await 语法而不是 Promise.then()/Promise.catch()

    const User = bookshelf.model('User', {
      tableName: 'user',
      hidden: ['password']
    });
    
    // main.js (in a async function)
    try {
      const newRow = await User.forge(attributes).save();
      console.log(newRow.id); // undefined
      const createdUser = await User.where(attributes).fetch();
      console.log(createdUser); // any id (1 for example)
    } catch (err) {
      // Handle errors
    }

    【讨论】:

      【解决方案2】:
      const User = bookshelf.model('User', {
        tableName: 'user',
        hidden: ['password']
      });
      
      // main.js
      const user = await new User().save(attributes);
      const {id} = user.toJSON()
      

      const User = bookshelf.model('User', {
        tableName: 'user',
        hidden: ['password']
      });
      
      // main.js
      User.forge(attributes)
          .save()
          .then(function (newRow) {
            let {id} = newRow.toJSON();
            console.log(id); // Should return the id
          })
          .catch(function (err) {
            // Handle errors
      });
      

      问题是你没有调用toJSON进行序列化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-16
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 2013-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多