DEV Community

Adeyemi Raji
Adeyemi Raji

Posted on

To set up a Node.js server with the Express web framework and a MongoDB database using Mongoose and MongoDB Atlas.

  1. First, make sure you have Node.js and the MongoDB Atlas CLI (command line interface) installed on your system. If you don't have them already, you can download and install them from their respective websites.

  2. Create a new Node.js project by running the following command in your terminal:

npm init -y

Enter fullscreen mode Exit fullscreen mode
  1. Install the required dependencies by running the following command:
npm install express mongoose

Enter fullscreen mode Exit fullscreen mode
  1. Create a new file called server.js and add the following code to it:
const express = require('express');
const mongoose = require('mongoose');

const app = express();

// Connect to the database
mongoose.connect('mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('Connected to MongoDB Atlas');
});

// Define your model(s)
const User = mongoose.model('User', {
  firstName: String,
  lastName: String
});

// Start the server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Enter fullscreen mode Exit fullscreen mode
  1. Replace and with the appropriate values for your MongoDB Atlas account. You can find these values in the "Connect" section of your cluster in the MongoDB Atlas dashboard.

  2. Run the server by executing the following command:

node server.js

Enter fullscreen mode Exit fullscreen mode

7.Your server should now be up and running, and you should be able to interact with the database using Mongoose. You can use the User model to create, read, update, and delete records in the users collection.
For example, you can add the following code to your server file to create a new user in the users collection:

app.post('/users', (req, res) => {
  const user = new User({
    firstName: 'John',
    lastName: 'Doe'
  });

  user.save((err, user) => {
    if (err) return console.error(err);
    res.send(user);
  });
});

Enter fullscreen mode Exit fullscreen mode

That will be all, hope you found it helpful ? happy coding...

Top comments (0)