basic-expressjs/lib/mongo.js

72 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2021-09-15 18:47:11 +00:00
const { MongoClient, ObjectId } = require('mongodb');
const { config } = require('../config');
const USER = encodeURIComponent(config.dbUser);
const PASSWORD = encodeURIComponent(config.dbPassword);
const DB_NAME = config.dbName;
const HOST = config.dbHost;
const PORT = config.dbPort;
// const MONGO_URI = `mongodb+srv://${USER}:${PASSWORD}@${HOST}/${DB_NAME}?retryWrites=true&w=majority`
const MONGO_URI = `mongodb://127.0.0.1:27017/${DB_NAME}`
class MongoLib {
constructor() {
this.client = new MongoClient(MONGO_URI, { useNewUrlParser: true });
this.dbName = DB_NAME;
}
connect() {
if (MongoLib.connection) return MongoLib.connection;
MongoLib.connection = new Promise((resolve, reject) => {
this.client.connect(err => {
if (err) {
reject(err);
}
console.log('MongoDB connected');
resolve(this.client.db(this.dbName))
});
});
return MongoLib.connection;
}
getAll(collection, query) {
return this.connect().then(db => {
return db.collection(collection).find(query).toArray();
});
}
get(collection, id) {
return this.connect().then(db => {
return db.collection(collection).findOne({_id: ObjectId(id)});
});
}
create(collection, data) {
return this.connect()
.then(db => {
return db.collection(collection).insertOne(data);
})
.then(result => result.insertedId);
}
update(collection, id, data) {
return this.connect()
.then(db => {
return db.collection(collection).updateOne({_id: ObjectId(id) }, { $set: data });
})
.then(result => result.upsertedId || id);
}
delete(collection, id) {
return this.connect()
.then(db => {
return db.collection(collection).deleteOne({_id: ObjectId(id)});
})
.then(() => id);
}
}
module.exports = MongoLib;