DEV Community

Cover image for MongoDB connect with a Node.js web server and Send your first data in Database: Atlas and Compass
Saiful Islam
Saiful Islam

Posted on

MongoDB connect with a Node.js web server and Send your first data in Database: Atlas and Compass

1#Directly sending data to mongodb atlas and compass

First set your mongodb atlas account and install mongodb compass as per your device configuration

In atlas website and compass software:-
1.After setting up your databases, using as per free tire option and click to connect button in atlas website first.
2.Then, will set up Collection name/database name and table name.(it is possible to setup by server code as well, all these are depends on coder)
3.After 1 and 2, Run the code(Before running the code install in terminal press:

npm install mongodb
Enter fullscreen mode Exit fullscreen mode

After installing then run the code:

node dbconnect.js
Enter fullscreen mode Exit fullscreen mode

Code:

`const { MongoClient } = require('mongodb');//By this-{}, installing mongodb class.

// Direct connection string with username and password
const url = 'mongodb+srv://mrx:JByoERjrLbSVNpmP@cluster0.klreadp.mongodb.net/myDatabase?retryWrites=true&w=majority';//from mongoDB Atlas url.
const dbName = 'myDatabase';// Database name

const client = new MongoClient(url);

async function connectToDatabase() {
    try {
        await client.connect();// Connect to the MongoDB server
        console.log('✅ Connected to MongoDB Atlas');

        const db = client.db(dbName);// Get the database instance
        const usersCollection = db.collection('users');// Get the 'users' collection -> table.

        const sampleUser = {
            name: 'Mitchell Johnson',
            email: 'jonson@example.com',
            age: 24,
            address: {
                street: '123 Main St',
                city: 'San Francisco',
                state: 'CA',
                zipCode: '94101'
            },
            hobbies: ['reasoning', 'travelling', 'coding','problem solving'],
            createdAt: new Date()
        };

        const result = await usersCollection.insertOne(sampleUser);//directly insert the sample user into the collection
        console.log(`✅ User inserted with ID: ${result.insertedId}`);

        const foundUser = await usersCollection.findOne({ name: 'Mitchell Johnson' });// Find the user we just inserted
        console.log('📦 Found user:', foundUser);

        return '✅ MongoDB operations completed';
    } catch (error) {
        console.error('❌ MongoDB connection error:', error);
    } finally {
        await client.close();
        console.log('🔒 Connection closed');
    }
}

connectToDatabase()
    .then(console.log)// Log the success message
    .catch(console.error);// Log any errors that occur during the connection or operations.
Enter fullscreen mode Exit fullscreen mode

After running this Output of Terminal:

Output of Compass and Atlas(same):

2#Using Mongoose schema(ORM) sending data to mongodb atlas and compass

Like same as First part as directly sending, Except:

Only install mongoose package by-

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

Run in terminal:

node file_mongoose.js
Enter fullscreen mode Exit fullscreen mode

Code:

const mongoose= require('mongoose');

const db = mongoose.connect('mongodb+srv://mrx:JByoERjrLbSVNpmP@cluster0.klreadp.mongodb.net/myDatabase?retryWrites=true&w=majority');

const model= mongoose.model('login', {username: String, email: String, password: String})//model schema is defined here.

const user = new model({//creating a new user instance based on the model schema.
    username: 'Stephen Hawkings',
    email: 'einstein@gmail.com',
    password: '7801'
});
user.save()
    .then(() => console.log('It is an event of Joy! that your effort is sucessful'))// message to be printed on successful save of user.
    .catch(err => console.error('Error saving user:', err));// failure message to be printed on unsuccessful save of user.
Enter fullscreen mode Exit fullscreen mode

Output would be same as Direct mongodb connection.

Top comments (0)