I need some help with mongodb.
I just started using it, and made a Cluster called db, with a database called discord-bot with a collection called users
This should make a database entry for every user, so here is my code
const { MongoClient } = require("mongodb");
const uri = "mongodb+srv://<My username>:<My password>#<My db url>?retryWrites=true&w=majority";
const client = new MongoClient(uri);
async function run(query) {
try {
await client.connect();
const database = client.db('discord-bot');
const collection = database.collection('users');
await collection.insertOne(query);
} finally {
await client.close();
}
}
botClient.users.cache.forEach(u => {
const q = { name: u.username }
run(q).catch(console.dir);
})
I think this code should work, but it is giving me this error
TypeError: Cannot read property 'maxWireVersion' of null
I can not find anything online about that error, can somebody help me figure out what that error is and how to fix it. (Also, i am using mongodb with discord.js, incase that is neccessary info)
I use this to connect to mongo DB
const MongoClient = require('mongodb').MongoClient;
var connection;
MongoClient.connect('your-db-uri', { useUnifiedTopology: true }, async function(err, client) {
if(err)throw err
console.log("Successfully Connected")
connection = client
})
Then you can use connection variable as global for all functions
Related
im using mongoclient and im sure that I have connection to the database
const client = new MongoClient(uri);
const datatbaseslist = client.db().admin().listDatabases();
datatbaseslist.databases.forEach(db => {
console.log($db.name)
});
I saw that code in a video of the mongodb and its not working.
thanks
I have tried looking for other versions to that line
const datatbaseslist = client.db().admin().listDatabases();
datatbaseslist.databases.forEach(db => {
console.log($db.name)
});
because im pretty sure that the problem is there.
I think your question title is saying one thing (collections) and your code is confusing this any another (databases).
A mongodb server can have multiple databases.
A database can have multiple collections.
You connect to the server using a client.
Normally if you want to know about the databases, you would use admin(). Or to connect to a specific database (although you can connect via URI), the you use db(dbName) from the client.
Once you have a db object, you can get the collections from there.
The below code shows you how to get both databases and collections.
const { MongoClient } = require('mongodb')
async function main () {
// Set config
const uri = 'mongodb://localhost:27017'
const client = new MongoClient(uri)
try {
// Connect to the MongoDB cluster
await client.connect()
// Get databases
const databasesList = await client.db().admin().listDatabases()
for (const dbName of databasesList.databases.map(db => db.name)) {
console.log('DB: ', dbName)
// Get collections for each database
const collections = await client.db(dbName).listCollections().toArray()
console.log('Collections:', collections.map(col => col.name).join(', '))
console.log('---------------------------------------------')
}
} catch (e) {
// Handle any erros
console.error(e)
} finally {
// Always close the connection to the database when finished
await client.close()
}
}
main().catch(console.error)
I have tried this in nodejs but i am getting undefined as output in my console
// Connect using a MongoClient instance
const MongoClient = require("mongodb").MongoClient;
const test = require("assert");
// Connection url
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "test";
// Connect using MongoClient
const mongoClient = new MongoClient(url);
mongoClient.connect(function (err, client) {
const db = client.db(dbName);
try {
db.collection("employeeDetails")
.find({})
.toArray(function (err, res) {
console.log(res);
});
} catch (e) {
console.log(e);
} finally {
client.close();
}
});
I have data in mongodb :
How do i get my employee details in my console Any help would be appreciated
You're closing the connection before getting the results. If you print err inside toArray() along with result, you will see below error -
MongoExpiredSessionError: Cannot use a session that has ended
This is happening because the db.collection("employeeDetails")... is getting called but waits for results in callback, till then it moves ahead and since after that statement you are exiting try-catch, you enter into finally which closes the session. When the db.collection... call is processed, this session is already ended and you see this error.
You can use async await. Modify your code as below -
// Connect using a MongoClient instance
const MongoClient = require("mongodb").MongoClient;
const test = require("assert");
// Connection url
const url = "mongodb://localhost:27017";
// Database Name
const dbName = "test";
// Connect using MongoClient
const mongoClient = new MongoClient(url);
mongoClient.connect(async function (err, client) {
const db = client.db(dbName);
try {
const result = await db.collection('employeeDetails').find({}).toArray();
console.log(result);
} catch (e) {
console.log(e);
} finally {
client.close();
}
});
In the line mongoClient.connect(async function (err, client).. we're using async before the callback function and later inside, we can just get the result using -
const result = await db.collection('employeeDetails').find({}).toArray();
After this console.log will print your results correctly.
This works for me
let result = await collection(collection).find(query).toArray()
I'm just starting to use Mongodb without mongoose (to get away from the schemas), and wanted to create a simple module with various exported functions to use in the rest of my app. I've pasted the code below.
The problem I'm having is that the databasesList.databases comes back as undefined, and I'm not sure why. There should be 2 databases on my cluster, and one collection in each database.
As a tangential question, I thought maybe I would check the collections instead (now commented out), but though I found this page (https://docs.mongodb.com/manual/reference/method/db.getCollectionNames/) the function getCollectionNames seems not to exist. Now I'm wondering if I'm using the wrong documentation and that is why my databases are coming back undefined.
const client = new MongoClient(uri)
const connection = client.connect( function (err, database) {
if (err) throw err;
else if (!database) console.log('Unknown error connecting to database');
else {
console.log('Connected to MongoDB database server');
}
});
module.exports = {
getDatabaseList: function() {
console.log('start ' + client);
databasesList = client.db().admin().listDatabases();
//collectionList = client.db().getCollectionNames();
//console.log("Collections: " + collectionList);
console.log("Databases: " + databasesList.databases);
//databasesList.databases.forEach(db => console.log(` - ${db.name}`));
}
}```
your code is correct Just need to change few things.
module.exports = {
getDatabaseList: async function() {
console.log('start ' + client);
databasesList = await client.db().admin().listDatabases();
//collectionList = await client.db().getCollectionNames();
//console.log("Collections: " + collectionList);
console.log("Databases: " + databasesList.databases);
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
}
}
You have to declare async function and use await also.
The async and await keywords enable asynchronous, promise-based behaviour to be written in a cleaner style, avoiding the need to explicitly configure promise chains.
You can use this modular approach to build your database access code:
index.js: Run your database application code, like list database names, collection names and read from a collection.
const connect = require('./database');
const dbFunctions = require('./dbFunctions');
const start = async function() {
const connection = await connect();
console.log('Connected...');
const dbNames = await dbFunctions.getDbNames(connection);
console.log(await dbNames.databases.map(e => e.name));
const colls = await dbFunctions.getCollNames(connection, 'test');
console.log(await colls.map(e => e.name));
console.log(await dbFunctions.getDocs(connection, 'test', 'test'));
};
start();
database.js:: Create a connection object. This connection is used for all your database access code. In general, a single connection creates a connection pool and this can be used throughout a small application
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017/';
const opts = { useUnifiedTopology: true };
async function connect() {
console.log('Connecting to db server...');
return await MongoClient.connect(url, opts );
}
module.exports = connect;
dbFunctions.js:: Various functions to access database details, collection details and query a specific collection.
module.exports = {
// return list of database names
getDbNames: async function(conn) {
return await conn.db().admin().listDatabases( { nameOnly: true } );
},
// return collections list as an array for a given database
getCollNames: async function(conn, db) {
return await conn.db(db).listCollections().toArray();
},
// return documents as an array for a given database and collection
getDocs: async function(conn, db, coll) {
return await conn.db(db).collection(coll).find().toArray();
}
}
I am trying out the MongoDB API and I ran into MongoError: topology was destroyed while trying to use the insertOne() function. I don't know what is going on as I am pretty new to this. Any suggestions or help would be appreciated.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://email:password#cluster0.9r3f9.mongodb.net";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(mongoError => {
const col = client.db("mc").collection("mc").insertOne({"license" : "1", "uuid" : 123})
console.log(col)
});
The client.connect() should accept both parameters error and client and use that object to execute the queries. Also since you are using mongodb driver natively (and not mongoose) you shouldn't need to use { useNewUrlParser: true }.
Even if this doesn't solve the problem, restart your mongodb instance and check.
const MongoClient = require("mongodb").MongoClient;
const uri = "mongodb+srv://email:password#cluster0.9r3f9.mongodb.net";
const client = new MongoClient(uri);
client.connect((err, client) => {
if(err) {
console.error("ConnectionError::", err);
return;
}
const db = client.db("mc");
db.collection("mc").insertOne({ license: "1", uuid: 123 }, (err, result) => {
console.log(result);
});
});
NOTE: .insertOne() is an async operation and will require a callback as well or async/await to correctly show to results of the query.
This is the error I am getting . please help to resolve this
Code
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://userName:password#saichaitanyacluster-1m22k.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
client.close();
});
You should add a check to confirm that there is no error in connection before calling client.db(). The connection code should be something like this:
// ...Everything that was here before
client.connect(err => {
if (err) {
console.log("There was an error connecting to the database");
// Any other logic that you want to use to handle the error should live here.
// Add a return statement to help avoid executing
// the code below that relies on a successful connection
return;
}
const collection = client.db("test").collection("devices");
client.close();
});
I hope this helps.