DEV Community

Rittwick Bhabak
Rittwick Bhabak

Posted on

Node.js Crash Course - Part 9 - MongoDB

  1. Open account on mongodb atlas
  2. Create cluster
  3. Create collection
  4. Set up connection
  5. Set up and get dbURI

Setting up connection in app.js

const dbURI = 'mongodb+srv://yourusername:yourpassword@nodetuts.3g4hc.mongodb.net/yourdatabasename?retryWrites=true&w=majority';
mongoose.connect(dbURI)
  .then(result=> app.listen(3000))
  .catch(err=> console.log('some error occurred'))
Enter fullscreen mode Exit fullscreen mode

.then(result=>app.listen(3000)) means after the database connection is made then app will start listening to the requests.

Setting up model

Create a file called 'blog.js' inside a folder '/models'.
Then in blog.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const blogSchema = new Schema({
    title:{
        type: String,
        required: true
    },
    snippet: {
        type: String,
        required: true
    },
    body:{
        type: String,
        required: true
    }
}, { timestamps: true });

const Blog = mongoose.model('Blog', blogSchema);
module.exports = Blog;
Enter fullscreen mode Exit fullscreen mode

We will create a model and the model will be built on a schema.
Creating a schema: const Schema = mongoose.Schema
and const blogSchema = new Schema({})

const Blog = mongoose.model('Blog', blogSchema); The second 'Blog' name is important. Mongoose will pluralize this and search a model of that name, i.e. 'Blogs' in server.

Getting and Saving Data

We can insert by the following way using .save() method.

app.get('/add-blog', (req, res) => {
    const blog = Blog({
        title: 'Blog Post 1',
        snippet: 'you can also drag a cover image',
        body: 'MongoDB provides high availability with replica sets'
    });

    blog.save()
        .then( result => res.send(result))
        .catch(err => console.log(err));
})
Enter fullscreen mode Exit fullscreen mode

We can retrive all the data by following way using .find() method

Blog.find()
        .then( results => res.send(results))
        .catch( err => console.log(err))
Enter fullscreen mode Exit fullscreen mode

We can retrieve single data by the following way using .fingById() method:

app.get('/single-blog', (req, res) => {
    Blog.findById('5fa27e3d1ca6c8027cc7497b')
        .then( result => res.send(result))
        .catch( err => console.log(err))
})
Enter fullscreen mode Exit fullscreen mode

Also we can sort the data:

Blog.find().sort({ createdAt: -1 })
    .then( results => res.send(results) )
    .catch( err => console.log(err) )
Enter fullscreen mode Exit fullscreen mode

-1 means descending order.

Top comments (0)