0% found this document useful (0 votes)
5 views

how to connect to a mongodb

The document provides code snippets for connecting a Node.js application to a MongoDB database. It demonstrates how to create a collection and insert a record into the database using the MongoDB Node.js driver. The code includes error handling and ensures the database connection is closed after operations are completed.

Uploaded by

jayanthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

how to connect to a mongodb

The document provides code snippets for connecting a Node.js application to a MongoDB database. It demonstrates how to create a collection and insert a record into the database using the MongoDB Node.js driver. The code includes error handling and ensures the database connection is closed after operations are completed.

Uploaded by

jayanthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

How to connect to a node.

js application to a mongodb database with suitable code:

App.js

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/mydb";

const client=new MongoClient(url);

const database="studentDB"

async function getData()

let result=await client.connect();

let dbo=result.db(database);

dbo.createCollection("Student_Info");

console.log("Collection created");

getData()

for Inserting a record into the database

const { MongoClient } = require('mongodb');

// Replace with your MongoDB connection string

const uri = 'mongodb://localhost:27017'; // or your MongoDB Atlas connection string

const client = new MongoClient(uri);

async function run() {

try {
// Connect to the MongoDB cluster

await client.connect();

console.log("Connected to MongoDB");

// Specify the database and collection

const database = client.db('myDatabase');

const collection = database.collection('myCollection');

// Insert a document

const doc = { name: "Alice", age: 25 };

const result = await collection.insertOne(doc);

console.log(`New document created with the following id: ${result.insertedId}`);

} catch (error) {

console.error("Error connecting to MongoDB", error);

} finally {

// Close the connection to the database

await client.close();

// Run the function

run().catch(console.dir);

You might also like