Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/lib/mongoDB.js
1126 views
1
const mongoose = require('mongoose')
2
const { Schema } = mongoose
3
4
module.exports = class mongoDB {
5
constructor(url, options = { useNewUrlParser: true, useUnifiedTopology: true }) {
6
this.url = url
7
this.data = this._data = this._schema = this._model = {}
8
this.db
9
this.options = options
10
}
11
async read() {
12
this.db = await mongoose.connect(this.url, { ...this.options })
13
this.connection = mongoose.connection
14
let schema = this._schema = new Schema({
15
data: {
16
type: Object,
17
required: true, //depends on whether the field is mandatory or not
18
default: {}
19
}
20
})
21
// this._model = mongoose.model('data', schema)
22
try { this._model = mongoose.model('data', schema) } catch { this._model = mongoose.model('data') }
23
this._data = await this._model.findOne({})
24
if (!this._data) {
25
this.data = {}
26
await this.write(this.data)
27
this._data = await this._model.findOne({})
28
} else this.data = this._data.data
29
return this.data
30
}
31
32
33
async write(data) {
34
if (!data) return data
35
if (!this._data) return (new this._model({ data })).save()
36
this._model.findById(this._data._id, (err, docs) => {
37
if (!err) {
38
if (!docs.data) docs.data = {}
39
docs.data = data
40
return docs.save()
41
}
42
})
43
}
44
}
45