Full-Stack Web Development with Vue.js and Node

(singke) #1
Introducing REST APIs Chapter 4

We can use the save query feature given by Postman to run those queries
in future as well. Just click the Save button, which is in the top right-hand
corner of the app. And create new queries as we go forward.

Fetching a single user

As mentioned in the HTTP verbs section, to fetch a single record from the collection, we
have to pass an id of the user in the parameter in order to get the user details. From the


preceding Postman response example, let's pick an id and use it to fetch the record of a


user. First, let's add the endpoint to our controller. In controllers/users.js, add the


following lines of code:


var User = require("../models/User");

module.exports.controller = (app) => {
// get all users
app.get('/users', (req, res) => {
User.find({}, 'name email', function (error, users) {
if (error) { console.log(error); }
res.send({
users: users
})
})
})

//get a single user details
app.get('/users/:id', (req, res) => {
User.findById(req.params.id, 'name email', function (error, user) {
if (error) { console.log(error); }
res.send(user)
})
})
}
Free download pdf