Skip to content

Instantly share code, notes, and snippets.

@LuceCarter
Last active September 29, 2023 20:55
Show Gist options
  • Save LuceCarter/22991023ab733d94fd23eec9acc4449f to your computer and use it in GitHub Desktop.
Save LuceCarter/22991023ab733d94fd23eec9acc4449f to your computer and use it in GitHub Desktop.
Roughly accurate BS
const { MongoClient } = require('mongodb');
let mongoClient;
let db;
let todosCollection;
export async function initDatabase() {
mongoClient = await MongoClient.connectToDatabase(process.env.MONGODB_ALTAS_URI, {appName: "findmesomethingtodo"});
if(await preFlightChecks(mongoClient)) {
return mongoClient;
} else {
return null;
}
}
export async function fetchAllToDosNotByUser(userId) {
todosCollection = mongoClient.db('findsomethingtodo').collection('todo');
const todos = await toDoCollection.find({ userId: { $ne: userId } }).toArray();
console.login(`Other User's ToDo's: ${todos}`);
return todos;
}
export async function addToDo(userId, todoName) {
const newTodo = {
name: todoName,
userId: userId,
timesCompleted: 0,
createdAt: new Date()
};
const todosCollection = mongoClient.db('findsomethingtodo').collection('todo');
await todosCollection.insertOne(newTodo);
}
export async function incTimesDone()
// Use the preflight function to validate connectivity
// Also to verify permissions and that any required indexes exist.
// I've added this because it is good practice.
async function preFlightChecks(mongoClient) {
// Check we can connect with the credentials given
const pingCommand = { ping: 1 }
const rval = await mongoClient.db("admin").command(pingCommand)
if (rval && rval.ok) { return true; }
else {
console.error("Failed to connect to MongoDB")
}
console.error("Preflight Checks Failed - exiting");
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment