To connect to MongoDB with ConnectCI, you’ll need to follow these steps:
- Install the MongoDB driver for Node.js using the following command:
npm install mongodb
- In your Node.js application, require the MongoDB driver by adding the following code at the top of your file:javascriptCopy code
const MongoClient = require('mongodb').MongoClient;
- Create a MongoDB client object by calling the
MongoClient.connect()
method, passing in your MongoDB connection string as the first argument. Your MongoDB connection string should include your database name, username, and password.arduinoconst uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true&w=majority'; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
- Use the
client.connect()
method to establish a connection to your MongoDB database. This method returns a Promise, so you can use theasync/await
syntax to wait for the connection to be established.javascriptawait client.connect(); console.log('Connected to MongoDB');
- Once the connection is established, you can use the
client.db()
method to access your database.arduinoconst database = client.db('<database>');
- Finally, you can use the
database.collection()
method to access a specific collection in your database.arduinoconst collection = database.collection('<collection>');
Here’s a sample code snippet that puts all these steps together:
javascriptCopy codeconst MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<database>?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function main() {
try {
await client.connect();
console.log('Connected to MongoDB');
const database = client.db('<database>');
const collection = database.collection('<collection>');
// Use the collection object to perform database operations
} catch (err) {
console.error(err);
} finally {
await client.close();
}
}
main();
Remember to replace <username>
, <password>
, <cluster>
, <database>
, and <collection>
with your own values.