sqltypescriptmariadbnestjstypeorm

Return inserted id with TypeORM & NestJS raw query: await connection.manager.query(`INSERT INTO


I'm looking to return the id or better yet, all information that was inserted, using a raw query with TypeORM and NestJS. Example as follows:

await connection.manager.query(`INSERT INTO...`)

When assigning the query to a constant and console logging it below, it does not yield any helpful information:

OkPacket {
    fieldCount: 0,
    affectedRows: 1,
    insertId: 0,
    serverStatus: 2,
    warningCount: 1,
    message: '',
    protocol41: true,
    changedRows: 0
}

As you can see, it returns no pertinent information, the insertId above is obviously incorrect, and it returns this every time, regardless of the actual parameters of the query.

I know with more typical TypeORM queries you can use .return(['name_of_column_you_want_returned']).execute() and it will return the relevant information just fine. Is there any way to do this with a raw query? Thank you!


Solution

  • tl;dr You're getting the raw mariadb driver response (OkPacket) from the INSERT command, and you'd need a new SELECT query to see the data.


    You're using the TypeORM EntityManager, and the docs don't mention a return value. Looking at the source code for query, the return type is any. Since it's a raw query, it probably returns an object based on the type of database you're using rather than having a standard format.

    In this case, you're using MariaDb, which returned an OkPacket. Here's the documentation: https://mariadb.com/kb/en/ok_packet/