簡體   English   中英

Knex.js 返回插入的記錄 ID

[英]Knex.js return inserted record ID

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

控制台日志 =>

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
}

弄清楚了。

需要將.returning('id')添加到查詢中。

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

在我使用 mysql 的情況下, await insert({...})返回一個帶有 id 作為單個元素的數組。 通過使用returning('id')我得到一個錯誤,說它不支持 mysql。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM