Skip to content

Instantly share code, notes, and snippets.

@josemunozr
Created July 28, 2020 12:30
Show Gist options
  • Save josemunozr/470b0598005f4d0126e941f5e4b846f6 to your computer and use it in GitHub Desktop.
Save josemunozr/470b0598005f4d0126e941f5e4b846f6 to your computer and use it in GitHub Desktop.
Implementación CRUD básico MongoDB
//CONFIG
PORT=
CORS=*
//MONGO
DB_USER=
DB_PASSWORD=
DB_HOST=
DB_NAME
require('dotenv').config();
const config = {
dev: process.env.NODE_ENV !== 'production',
port: process.env.PORT || 3000,
dbUser: process.env.DB_USER,
dbPassword: process.env.DB_PASSWORD,
dbHost: process.env.DB_HOST,
dbName: process.env.DB_NAME
};
module.exports = { config };
const { MongoClient, ObjectId } = require('mongodb');
const { config } = require('../config/index');
const USER = encodeURIComponent(config.dbUser);
const PASSWORD = encodeURIComponent(config.dbPassword);
const DB_NAME = config.dbName;
const MONGO_URI = `mongodb+srv://${USER}:${PASSWORD}@${config.dbHost}/${config.dbName}?retryWrites=true&w=majority`;
class MongoLib {
constructor() {
this.client = new MongoClient(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
this.dbName = DB_NAME;
}
connect() {
if (!MongoLib.connection) {
MongoLib.connection = new Promise((resolve, reject) => {
this.client.connect((err) => {
if (err) reject(err);
console.log('Connection succefully to mong');
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 }, { upsert: true });
})
.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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment