use D1 DB in worker (no wrangler etc, just JS)

hey there, noobie here. There are multiple tutorials online how to set up the D1 DB with a worker using wrangler, nodejs etc., however i just want to be able to use all the db related stuff within my js file, so no typescript. I went ahead and added the database via DB Database bindings in the settings of the worker, however any request i do in js returns empty data:
const { results } = await env.DB.prepare('SELECT * FROM user').all();
const json = await Response.json(results);
const jjson = JSON.stringify(json);
console.log(jjson);
const { results } = await env.DB.prepare('SELECT * FROM user').all();
const json = await Response.json(results);
const jjson = JSON.stringify(json);
console.log(jjson);
and yes, the DB is called user, the environment variable in the settings is DB. Am i missing something?
7 Replies
kian
kian13mo ago
Response.json is a static method to return a Response. That isn't something you can stringify.
Spuckwaffel
SpuckwaffelOP13mo ago
oh i see. how can i get the db result as a string?
kian
kian13mo ago
Just remove the const json line Stringifying results is all you need to do
Spuckwaffel
SpuckwaffelOP13mo ago
awesome! Thank you very much.
kian
kian13mo ago
If you're trying to return it to the user, you can do return Response.json(results) from your fetch handler return Response.json(obj) is basically return new Response(JSON.stringify(obj))
Spuckwaffel
SpuckwaffelOP13mo ago
alright, thanks!
Hello, I’m Allie!
Plus a content-type header

Did you find this page helpful?