@addison
To read data from MongoDB in a Discord.js bot, you will need to first connect your bot to the MongoDB database and then use MongoDB queries to retrieve the data you need. Here's a basic example of how you can achieve this:
1
|
npm install mongodb |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const { MongoClient } = require('mongodb'); const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); async function connectToDatabase() { try { await client.connect(); console.log('Connected to MongoDB'); } catch (error) { console.error('Error connecting to MongoDB:', error); } } |
Replace mongodb://localhost:27017
with your MongoDB URI if it's hosted on a different server.
1 2 3 4 5 6 7 8 9 10 11 |
async function readDataFromCollection(collectionName) { const database = client.db('yourDatabaseName'); const collection = database.collection(collectionName); const result = await collection.find({}).toArray(); console.log(result); } connectToDatabase().then(() => { readDataFromCollection('yourCollectionName'); }); |
Replace yourDatabaseName
with the name of your MongoDB database and yourCollectionName
with the name of the collection from which you want to fetch data.
Remember to handle errors appropriately and close the MongoDB connection when you no longer need it.