【问题标题】:Knex.js return inserted record IDKnex.js 返回插入的记录 ID
【发布时间】:2022-01-22 05:15:19
【问题描述】:

我正在向 quoteNotes 表中插入一条注释。当我插入它并控制台记录 res.它没有给我插入笔记的记录。

router.post('/:id/notes', (req, res) => {
  const {id} = req.params;
  const note = req.body;
  note.quote_id = id

  // if(note.note === "") return res.status(422)
  //   .json({message: 'Note cannot be empty'});

  Quotes.addNote(note).then((quoteNote) => {
    console.log(quoteNote)
    res.status(200).json(quoteNote);
  });
});

console.log =>

Result {
  command: 'INSERT',
  rowCount: 1,
  oid: 0,
  rows: [],
  fields: [],
  _parsers: undefined,
  _types: TypeOverrides {
    _types: {
      getTypeParser: [Function: getTypeParser],
      setTypeParser: [Function: setTypeParser],
      arrayParser: [Object],
      builtins: [Object]
    },
    text: {},
    binary: {}
  },
  RowCtor: null,
  rowAsArray: false
}

【问题讨论】:

    标签: javascript mysql postgresql express knex.js


    【解决方案1】:

    想通了。

    需要在查询中添加.returning('id')

    function addNote(data) {
      return db('quote_notes')
        .insert(data)
        .returning('id');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2011-05-05
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多