|
|
const mongoose = require('mongoose'); |
|
|
const { Schema } = mongoose; |
|
|
|
|
|
module.exports = class mongoDB { |
|
|
constructor(url, options = { useNewUrlParser: true, useUnifiedTopology: true }) { |
|
|
this.url = url; |
|
|
this.data = this._data = this._schema = this._model = {}; |
|
|
this.db = null; |
|
|
this.options = options; |
|
|
} |
|
|
|
|
|
async read() { |
|
|
|
|
|
try { |
|
|
this.db = await mongoose.connect(this.url, { ...this.options }); |
|
|
this.connection = mongoose.connection; |
|
|
|
|
|
|
|
|
this._schema = new Schema({ |
|
|
data: { |
|
|
type: Object, |
|
|
required: true, |
|
|
default: {} |
|
|
} |
|
|
}); |
|
|
|
|
|
|
|
|
try { |
|
|
this._model = mongoose.model('data', this._schema); |
|
|
} catch (error) { |
|
|
|
|
|
this._model = mongoose.model('data'); |
|
|
} |
|
|
|
|
|
|
|
|
this._data = await this._model.findOne({}); |
|
|
if (!this._data) { |
|
|
this.data = {}; |
|
|
await this.write(this.data); |
|
|
this._data = await this._model.findOne({}); |
|
|
} else { |
|
|
this.data = this._data.data; |
|
|
} |
|
|
return this.data; |
|
|
} catch (error) { |
|
|
console.error('Error connecting to MongoDB:', error); |
|
|
throw error; |
|
|
} |
|
|
} |
|
|
|
|
|
async write(data) { |
|
|
if (!data) return null; |
|
|
|
|
|
if (!this._data) { |
|
|
|
|
|
const newData = new this._model({ data }); |
|
|
return await newData.save(); |
|
|
} |
|
|
|
|
|
|
|
|
try { |
|
|
const docs = await this._model.findById(this._data._id); |
|
|
if (!docs) throw new Error('Document not found'); |
|
|
|
|
|
|
|
|
docs.data = { ...docs.data, ...data }; |
|
|
return await docs.save(); |
|
|
} catch (error) { |
|
|
console.error('Error writing to MongoDB:', error); |
|
|
throw error; |
|
|
} |
|
|
} |
|
|
}; |