Updating a collection

Once we have the route to save a new entry, the next logical step is to create our route that will allow us to update an entry. We’ll continue to write the code to modify a collection item in our angcms/routes/api.js file as follows:

router.post('/pages/update', function(request, response) {
    var id = request.body._id;

    Page.update({
        _id: id
    }, {
        $set: {
            title: request.body.title,
            url: request.body.url,
            content: request.body.content,
            menuIndex: request.body.menuIndex,
            date: new Date(Date.now())
        }
    }).exec();
    response.send("Page updated");
});

Deleting a collection item

Next comes the route to delete an item; while continuing to work on the same file, we add the following code:

router.get('/pages/delete/:id', function(request, response) {
    var id = request.params.id;
    Page.remove({
        _id: id
    }, function(err) {
        return console.log(err);
    });
    return response.send('Page id- ' + id + ' has been deleted');
});

Ensure that the code is working by testing it with a REST client or typing in the route URL in a browser window along with a valid ID.

Displaying a single record

Next, we will write the route to fetch the data for an individual page on the admin side.

We’ll continue by adding the following code to our api.js file:

router.get('/pages/admin-details/:id', function(request, response) {
    var id = request.params.id;
    Page.findOne({
        _id: id
    }, function(err, page) {
        if (err)
            return console.log(err);
        return response.send(page);
    });
});

We use the get method here and pass the ID as a request parameter. We then run the findOne method to pull up a single record that matches the ID and return that as a response.

You can easily verify this route by simply appending the ID to the URL endpoint as follows:

http://localhst:3000/api/pages/view/<_id>.

On similar lines, we will also create another route to fetch the page contents for the frontend. Here, in the following code, we will use the URL as a parameter to fetch the data because we would like our frontend to show SEO-friendly URLs:

router.get('/pages/details/:url', function(request, response) {
    var url = request.params.url;
    Page.findOne({
        url: url
    }, function(err, page) {
        if (err)
            return console.log(err);
        return response.send(page);
    });
});