Created
January 29, 2020 20:23
-
-
Save olafkotur/757b9671f539baa2a8c4a516649e2736 to your computer and use it in GitHub Desktop.
Service for running simple MongoDB functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MongoClient = require('mongodb').MongoClient; | |
const url = process.env.MONGODB_URI || 'mongodb://localhost:27017/'; | |
let database: any = null; | |
export const MongoService = { | |
connect: () => new Promise((resolve: any) => { | |
MongoClient.connect(url, { useUnifiedTopology: true }, async (error: Error, db: any) => { | |
if (error) { | |
throw error; | |
} | |
database = db.db('data') | |
console.log(`MongoService: Succesfully connected to database`) | |
resolve(true); | |
}); | |
}), | |
insertOne: async (collection: string, data: any) => { | |
await database.collection(collection).insertOne(data, (error: Error) => { | |
if (error) { | |
throw error; | |
} | |
console.log('MongoService: Added 1 document'); | |
}); | |
}, | |
insertMany: async (collection: string, data: any) => { | |
await database.collection(collection).insertMany(data, (error: Error) => { | |
if (error) { | |
throw error; | |
} | |
console.log(`MongoService: Added ${data.length} documents`); | |
}); | |
}, | |
updateOne: async (collection: string, query: any, data: any) => { | |
await database.collection(collection).replaceOne(query, data, (error: Error) => { | |
if (error) { | |
throw error; | |
} | |
console.log('MongoService: Updated 1 document'); | |
}); | |
}, | |
findOne: async (collection: string, query: any) => { | |
return new Promise((resolve: any) => { | |
database.collection(collection).findOne(query, (error: Error, res: any) => { | |
if (error) { | |
throw error; | |
} | |
resolve(res); | |
}); | |
}); | |
}, | |
findMany: async (collection: string, query: any) => { | |
return new Promise((resolve: any) => { | |
database.collection(collection).find(query, (error: Error, res: any) => { | |
if (error) { | |
throw error; | |
} | |
resolve(res.toArray()); | |
}); | |
}); | |
}, | |
deleteOne: async (collection: string, query: any) => { | |
database.collection(collection).deleteOne(query, (error: Error) => { | |
if (error) { | |
throw error; | |
} | |
}); | |
}, | |
deleteMany: async (collection: string, query: any) => { | |
database.collection(collection).deleteMany(query, (error: Error) => { | |
if (error) { | |
throw error; | |
} | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment