60 lines
No EOL
1.7 KiB
JavaScript
60 lines
No EOL
1.7 KiB
JavaScript
const Mongoose = require(`mongoose`);
|
|
const CustomErrors = require(`../../utilities/errors.JS`);
|
|
|
|
class DBManagement {
|
|
/*
|
|
Begin the connection.
|
|
|
|
@param {string} DOMAIN the domain
|
|
@param {string} DBNAME the database name
|
|
*/
|
|
constructor (DOMAIN, DBNAME) {
|
|
const throwError = (ERROR) => {throw ERROR;};
|
|
|
|
this[`state`] = Mongoose.connect(`mongodb://${DOMAIN}/${(DBNAME) ? DBNAME : ""}`, { useNewUrlParser: true, useUnifiedTopology: true }).then((CONNECTION) => {
|
|
this[`connection`] = CONNECTION.connection;
|
|
console.log(`Connection successful.`);
|
|
}).catch(throwError);
|
|
};
|
|
|
|
/*
|
|
Establish the schema and collection. The result is stored in `this.#status`.
|
|
|
|
@param {string} COLLECTION the name of the collection
|
|
@param {object} SCHEMA the scehma
|
|
*/
|
|
configure (COLLECTION, SCHEMA) {
|
|
this[`schema`] = new Mongoose.Schema(SCHEMA);
|
|
this[`collection`] = COLLECTION;
|
|
this.state.then(() => {
|
|
this.model = this[`connection`].model(this[`collection`], this[`schema`]);
|
|
})
|
|
}
|
|
|
|
/*
|
|
Find based on corresponding details.
|
|
|
|
@param {object} CRITERIA the search criteria
|
|
@param {number} SIZE the size of the search
|
|
@return {object} the search results
|
|
*/
|
|
async search(CRITERIA = {}, SIZE) {
|
|
await this.state;
|
|
let RESULT = [];
|
|
|
|
if ((CRITERIA && CRITERIA instanceof Object) ? !(Object.keys(CRITERIA).length) : true) {
|
|
console.log(`Searching all...`);
|
|
RESULT = await this.model.find();
|
|
} else if (CRITERIA instanceof Object) {
|
|
RESULT = await this.model.find(CRITERIA);
|
|
}
|
|
|
|
if (RESULT.length && (SIZE) ? (SIZE > 0 && SIZE < RESULT.length) : false) {
|
|
RESULT = RESULT.slice(0,SIZE);
|
|
}
|
|
|
|
return RESULT;
|
|
};
|
|
}
|
|
|
|
module.exports = DBManagement; |