I'm setting up a mongoDB endpoint with NodeJS. Implementing this backend
I seem to have a problem with the code where the function static async injectDB
sets a global variable let restaurants
which another function static async getRestaurants
accesses, but then it turned into undefined
import mongodb from "mongodb"
const ObjectId = mongodb.ObjectID
let restaurants
export default class RestaurantsDAO {|
static async injectDB(conn) {
if (restaurants) {
return
}
try {
restaurants = await conn.db(process.env.RESTREVIEWS_NS).collection("restaurants")
} catch (e) {
console.error(
`Unable to establish a collection handle in restaurantsDAO: ${e}`,
)
}
}
static async getRestaurants({
filters = null,
page = 0,
restaurantsPerPage = 20,
} = {}) {
console.log(restaurants) // undefined
...
getRestaurants
is of course called at a much later point than injectDB
, if I console.log(restaurants)
in that function, it writes out its values. But its undefined when the other function is called. Why is that?
The injectDB
function is called at server start, while the getRestaurants
is called when someone acceesses the endpoint.
An alternative solution is to open the connection to DB in the getRestaurants
function, is that best practice?
See full code for restaurantsDAO.js