Build a simple blog with Node.js, Express, MongoDB (Part 5)


mongoose https://www.npmjs.com/package/mongoose is elegant mongodb object modeling for node.js

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
Read the docs http://mongoosejs.com/docs/guide.html

At first, add the following to server.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

mongoose.connect(url).then((result) => {}, (err) => {
  return console.log("Can't connect to MongoDB.");
});

var Post = mongoose.model('Post', {
  title: {
    type: String,// Read more http://mongoosejs.com/docs/schematypes.html
    trim: true,// boolean, whether to always call .trim() on the value
    required: true// boolean or function, if true adds a required validator for this property
  },
  content: {
    type: String,
    trim: true,
    required: true
  }
});


and delete the line:
const {MongoClient, ObjectId} = require('mongodb');

then we update our code to:
  • Create a new post
  • Display a list of all posts
  • Display a specific post
  • Update a specific post
  • Delete a specific post
Let's begin!

Create a new post

Change:
app.post('/posts', (req, res) => {
// ...
});

to:
app.post('/posts', (req, res) => {
  var post = new Post({
    title: req.body.title,
    content: req.body.content
  });
  post.save().then((doc) => {
    res.send(doc);
  }, (err) => {
    res.send('An error has been occurred while creating a new post.');
  });
});

Open postman and test:

Then open Robomongo to check:

Display a list of all posts

Change:
app.get('/posts', (req, res) => {
// ...
});

to:
app.get('/posts', (req, res) => {
  Post.find().then((docs) => {
    res.send(docs);
  }, (err) => {
    res.send('An error has been occurred while displaying a list of all posts.');
  });
});


Open postman and test:

Display a specific post

Change:
app.get('/posts/:id', (req, res) => {
// ...
});


to:
app.get('/posts/:id', (req, res) => {
  Post.findOne({_id: req.params.id}).then((doc) => {
    res.send(doc);
  }, (err) => {
    res.send('An error has been occurred while displaying a specific post.');
  });
});


Open postman and test:

Update a specific post

Change:
app.patch('/posts/:id', (req, res) => {
// ...
});

to:
app.patch('/posts/:id', (req, res) => {
  Post.updateOne(
    {_id: req.params.id},
    {
      $set: {
        title: req.body.title,
        content: req.body.content
      }
    }
  ).then((result) => {
    res.send(result);
  }, (err) => {
    res.send('An error has been occurred while updating a specific post.');
  });
});


Open postman and test:

Then open Robomongo to check:

Delete a specific post

Change:
app.delete('/posts/:id', (req, res) => {
// ...
});
to:
app.delete('/posts/:id', (req, res) => {
  Post.deleteOne({_id: req.params.id}).then((result) => {
    res.send(result);
  }, (err) => {
    res.send('An error has been occurred while deleting a specific post.');
  });
});


Open postman and test:

Then open Robomongo to check:

Mongoose

With Mongoose your code looks clean. But what did "type: String", "trim: true" and "required: true" work?

type: String

When you post other types (number in my case):
Mongoose will convert it to string:

trim: true

required: true

Let's remove the content from our request and guess what will happen?

It's a common message for all cases. If you want to change, do it your self! It's a challenge for you!

If you are already familiar with Promises, you will familiar with then(fulfilled, rejected) syntax. It not, read more https://www.promisejs.org/

Part 6: http://blog.alphaplus.vn/2017/09/build-simple-blog-with-nodejs-express-mongodb-part-6.html
See you then!

No comments:

Post a Comment