Search code examples
javascriptpostgresqlsql-insertdefaultknex.js

How can I use DEFAULT values via knex insert?


My goal is to dynamically insert data into a table via knex.

Code looks like this:

const knexService = require("../knexService.js")


async function insertObjectToKnex() {
    const insertObject = {
        id: "DEFAULT",
        someKey: "someValue"
    };

    await knexService.db("table").insert(inserObject);
}

On DEFAULT the next free id should be used as database id - table is configured and it works with raw sql. With knex.js I get the following error:

invalid input syntax for type integer: "DEFAULT"

Using the useNullAsDefault: true, config is not possible, because the id is not nullable.

How can I trigger the default value in knex - I did not find anything in the documentation or with google, that could at least give a hint to this issue!


Solution

  • While it is not mentioned in the documentation of knex.js one should simply not add fields with a DEFAULT assignement to a query. This will set the default value to the row column.