Book Image

Express.js Blueprints

By : Ben Augarten, Marc Kuo, Eric Lin, Aidha Shaikh, Fabiano Pereira Soriani, Geoffrey Tisserand, Chiqing Zhang, Kan Zhang
Book Image

Express.js Blueprints

By: Ben Augarten, Marc Kuo, Eric Lin, Aidha Shaikh, Fabiano Pereira Soriani, Geoffrey Tisserand, Chiqing Zhang, Kan Zhang

Overview of this book

<p>APIs are at the core of every serious web application. Express.js is the most popular framework for building on top of Node.js, an exciting tool that is easy to use and allows you to build APIs and develop your backend in JavaScript. Express.js Blueprints consists of many well-crafted tutorials that will teach you how to build robust APIs using Express.js.</p> <p>The book covers various different types of applications, each with a diverse set of challenges. You will start with the basics such as hosting static content and user authentication and work your way up to creating real-time, multiplayer online games using a combination of HTTP and Socket.IO. Next, you'll learn the principles of SOA in Node.js and see them used to build a pairing as a service. If that's not enough, we'll build a CRUD backend to post links and upvote with Koa.js!</p>
Table of Contents (14 chapters)

Generating unique IDs


In both our movie and actor schemas, we used a plugin called generateId().

While MongoDB automatically generates ObjectID for each document using the _id field, we want to generate our own IDs that are more human readable and hence friendlier. We also would like to give the user the opportunity to select their own id of choice.

However, being able to choose an id can cause conflicts. If you were to choose an id that already exists, your POST request would be rejected. We should autogenerate an ID if the user does not pass one explicitly.

Without this plugin, if either an actor or a movie is created without an explicit ID passed along by the user, the server would complain since the ID is required.

We can create middleware for Mongoose that assigns an id before we persist the object as follows:

// /src/models/plugins/generateId.js 
module.exports = function() {

return function generateId(schema){ 
  schema.pre('validate',function(next, done) {
    var instance = this; 
...