I am building a slack copy cat app for practice and want to implement the ability for users to create their own messaging space. When creating a message space, a unique key is created and stored to my database. My plan is to use these unique keys to serve the same html page that has the messaging functionality. In theory this would work, but I am having trouble retrieving the keys AND using them to route to my message.html file. Is there a way to run my server, retrieve the keys and store them to a global variable THEN route to the html page? I'm using Node, Express and MongoDB.
Here is what my code looks like on the back end to retrieve the keys:
var dbKeys = [];
db.messageSpaces.find({}, {"_id": 0, "name": 0}, function(error, data) {
if (error) {
console.log(error);
}
else {
for (var i = 0; i < data.length; i++) {
dbKeys.push(data[i].key);
}
}
});
And how I am attempted to route them:
for (var i = 0; i < dbKeys.length; i++) {
app.get(`/${dbKeys[i]}`, function(req, res) {
res.sendFile(path.join(__dirname, "public/message.html"));
});
}