While it’s recommended to isolate database calls to your getters and setters in your API, you can also access your database directly in a route if needed (e.g., when exposing a public developer API).
Your database can be accessed in two ways:
- Via the global
process.databases.<provider>
object. - Via its alias at
req.context.<provider>
.
Both methods are identical and are provided for convenience.
Example Usage
Accessing MongoDB via process in a route
/index.server.js
import joystick from '@joystick.js/node';
joystick.app({
routes: {
'/': async (req = {}, res = {}) => {
const books = await process.databases.mongodb.collection('books').find().toArray();
return res.status(200).send(books);
},
},
});
Accessing MongoDB via req.context in a route
/index.server.js
import joystick from '@joystick.js/node';
joystick.app({
routes: {
'/': async (req = {}, res = {}) => {
const books = await req.context.mongodb.collection('books').find().toArray();
return res.status(200).send(books);
},
},
});