'prisma findMany not returning id's of rows
Using prisma findMany to fetch rows from postgres database, but it's not returning the actual id of the row, just the other columns. I need the id so that I can pass that the frontend can use it for CRUD operations, is there a way to return those ID's?
const bookList = await prisma.books.findMany({
where: {
author_id: "123",
}
});
schema
model books {
id String @id @default(uuid())
name String @db.VarChar(50)
author_id String
}
Expected response
[{
"id": "some-uid",
"name": "some-book-name"
}]
^ it includes the id field, which I'm currently not getting
Solution 1:[1]
The default behaviour is to return all the fields in findMany but you can explicitly select fields that should be returned by select clause.
Here is an example:
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// A `main` function so that you can use async/await
async function main() {
// ... you will write your Prisma Client queries here
const createBook = await prisma.books.create({
data: {
name: 'book1',
author_id: '1',
},
});
console.log('createBook:',createBook);
const books = await prisma.books.findMany({
where: {
author_id: '1',
},
select: {
name: true,
author_id: true,
id: true,
},
});
console.log('books:',books);
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});
Here's the response
createBook: {
id: '04a86b46-0348-4aa3-99d4-9a28365c020c',
name: 'book1',
author_id: '1'
}
books: [
{
name: 'book1',
author_id: '1',
id: '04a86b46-0348-4aa3-99d4-9a28365c020c'
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nurul Sundarani |
