wolfcountBot/dbinit.js

68 lines
2.5 KiB
JavaScript
Raw Normal View History

2023-04-26 04:02:43 -04:00
require('dotenv').config();
const mongoose = require('mongoose');
const Wolfcount = require('./models/wolfcount');
2024-03-03 05:45:24 -05:00
const dblocation = process.env.DBLOCATION
2023-04-26 04:02:43 -04:00
try {
2024-03-03 05:45:24 -05:00
if (dblocation === 'selfhosted') {
const uri = `mongodb://${process.env.MONGODBUSER}:${process.env.MONGODBPASS}@${process.env.MONGODBHOST}/${process.env.DATABASE}`
mongoose.connect(`${uri}`, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('');
console.log(`Connected to the selfhosted database`);
}).catch((error) => {
console.log(`Failed to connect to the database`);
console.log(error);
});
} else if (dblocation === 'cloud') {
const uri = `mongodb+srv://${process.env.MONGODBUSER}:${process.env.MONGODBPASS}@${process.env.MONGODBCLUSTER}/${process.env.DATABASE}?retryWrites=true&w=majority`
mongoose.connect(`${uri}`, {
2023-08-13 08:33:49 -04:00
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('');
console.log(`Connected to the database`);
}).catch((error) => {
console.log(`Failed to connect to the database`);
console.log(error);
});
} else {
console.error(`Failed to connect to the database, it is possible that the host option is not available`);
}
2023-04-26 04:02:43 -04:00
// Wait a few seconds bfore execution
setTimeout(function() {
// ensure that the bot stats document exists
const wolfcount = new Wolfcount({
count: 0,
2023-04-26 05:32:56 -04:00
validation: "wolfcount"
2023-04-26 04:02:43 -04:00
});
wolfcount.save().then(() => {
console.log('Count document saved successfully into the database!');
Wolfcount.find().then((document) => {
console.log(document);
}).catch((err) => {
console.log('Failed to retrieve document from the database', err)
});
}).catch(err => {
console.log('Error while saving the count document', err);
});
}, 3000);
setTimeout(function() {
try {mongoose.disconnect();}
catch(err){console.log('Error while disconnecting from the database', err);}
}, 3000);
setTimeout(function() {
console.log('Collection and document saved successfully into the database. Succesfully closed the connection to the db!');
}, 4000);
}
catch(err) {
console.log('Error while connecting to the database', err);
}