Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

Using Mongoose Models with the POST Endpoint

Now requiring this module will give you the Post model, which you can use inside of your endpoint to create posts.

In server.js, change your app.post(‘/api/posts’) endpoint to the following:

var Post = require('./models/post')
app.post('/api/posts', function (req, res, next) {
  var post = new Post({
    username: req.body.username,
    body: req.body.body
  })
  post.save(function (err, post) {
    if (err) { return next(err) }
    res.json(201, post)
  })
})

First, you require the Post model. When a request comes in, you build up a new instance of the Post model with new Post(). Then, you save that Post model and return a JSON representation of the model to the user with status code 201.

While it isn’t totally necessary to return the JSON here, I like for my create API actions to do so. The client can sometimes make use of it. It might be able to use the _id field or show data that the server generated (such as the date field, for example).

Note the err line. In Node, it’s common for code to return callbacks like this that start with an error argument, and then the data is returned. It’s your responsibility to check whether there is an error message and do something about it. In this case, you call the next() callback with an argument, which triggers a 500 in Express. An error in this case would typically mean the database was having issues. Other programming languages use exceptions to handle errors like this, but Node.js made the design decision to go with error objects because of its asynchronous nature. It’s simply not possible to bubble up an exception with evented code like Node.js.

Go ahead and hit this endpoint again with curl or Postman. (Make sure you first restart your server. Later you’ll see how to automatically restart it with nodemon.)

$ curl -v -H "Content-Type: application/json" -XPOST --data "{\"username\":\"dickeyxxx\", \"body\":\"node rules!\"}" localhost:3000/api/posts

You should see a response like the following (make sure you’ve started your Mongo server):

> POST /api/posts HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:3000
> Accept: */*
> Content-Type: application/json
> Content-Length: 46
>
* upload completely sent off: 46 out of 46 bytes
< HTTP/1.1 201 Created
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 120
< Date: Sun, 22 Jun 2014 00:41:55 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
{"__v":0,"username":"dickeyxxx","body":"node rules!","_id": "53a62653fa305e5ddb318c1b","date":"2014-06-22T00:41:55.040Z"}

Since you see an _id field coming back, I’m pretty sure it’s working. Just to be sure, though, let’s check the database directly with the mongo command:

$ mongo social
MongoDB shell version: 2.6.1
connecting to social
> db.posts.find()
{ "_id" : ObjectId("53a62653fa305e5ddb318c1b"), "username" : "dickeyxxx", "body" : "node rules!", "date" : ISODate("2014-06-22T00:41:55.040Z"), "__v" : 0 }

Looks like it made it into the database!

Now, let’s update the GET request to read from the database:

app.get('/api/posts', function (req, res, next) {
  Post.find(function(err, posts) {
    if (err) { return next(err) }
    res.json(posts)
  })
})

This one is similar to the last one. Call find on the Post model; then, when the request returns, render out the posts as JSON (so long as no error was returned). Go back to your web browser and reload http://localhost:3000/api/posts to see it in action.

You now have a full API you can read and write from in order to support your Angular app.

Here is the final server.js:

var express = require('express')
var bodyParser = require('body-parser')
var Post = require('./models/post')

var app = express()
app.use(bodyParser.json())

app.get('/api/posts', function (req, res, next) {
  Post.find(function(err, posts) {
    if (err) { return next(err) }
    res.json(posts)
  })
})

app.post('/api/posts', function (req, res, next) {
  var post = new Post({
    username: req.body.username,
    body: req.body.body
  })
  post.save(function (err, post) {
    if (err) { return next(err) }
    res.json(201, post)
  })
})

app.listen(3000, function () {
  console.log('Server listening on', 3000)
})
  • + Share This
  • 🔖 Save To Your Account