Node.js Tips

Node.js Tips — Express Templates and Requests, and MongoDB Queries

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Close the Express Server

If we need to close the Express server, we just call close on it to close it.

It’s returned from listen and it’s an HTTP server.

For instance, we can write:

const server = app.listen(3000);

Full Text Search in MongoDB and Mongoose

We can do a search on Mongoose by creating an index on the identifier of the schema.

Indexes will speed up searches.

For instance, we can write:

const schema = new Schema({
  name: String,

  name: 'text',

Then we can write:

    $text: {
      $search: searchString
  .exec((err, docs) => {

to do the search.

We use the $search operator to do a search on the entry.

skip skip the number of entries given in the argument.

limit limits the number of arguments.

Get the Domain that Originated the Request in Express

We can use req.get to get the hostname from the host header.

We can also use thr origin header for cross-origin requests.

To get the host header, we write:

const host = req.get('host');

And we write:

const origin = req.get('origin');

to get the origin.

Accessing Express.js Local Variables on Client-Side JavaScript

We can pass our data from our template and then parse it in there.

To do that, we write:

 const localData =!{JSON.stringify(data)}

We stringified the data so that it’ll be interpolated in the template.

Add Class Conditionally with Jade/Pug

To add a class conditionally, we can write:

div.collapse(class=typeof fromEdit === "undefined" ? "edit" : "")

We put out JavaScript expression right inside the parentheses and it’ll interpolate the class name for us.

Store DB Config in a Node or Express App

We can store our config in a JSON file.

For instance, we can write:

const fs = require('fs'),
configPath = './config.json';
const parsed = JSON.parse(fs.readFileSync(configPath, 'UTF-8'));
exports.config = parsed;

We read the config with readFileSync and then call JSON.parse on the returned text string.

Exclude Some Fields from the Document with Mongoose

To exclude some fields from being returned, we convert it in the tranform method by using the delete on it to remove the property we want.

For instance, we can write:

UserSchema.set('toJSON', {
  transform(doc, ret, options) {
    delete ret.password;
    return ret;

We call set to add a method with the transform method to transform the data.

ret has the returned result.

Then we call delete on it.

Listen on HTTP and HTTPS for a Single Express App

We can listen to HTTP and HTTPS with one Express app.

To listen to HTTP requests, we just have to read in the private and certificate files.

Then we can create a server with them.

For instance, we can write:

const express = require('express');
const https = require('https');
const http = require('http');
const fs = require('fs');
const  app = express();

const options = {
  key: fs.readFileSync('/path/key.pem'),
  cert: fs.readFileSync('/path/cert.pem'),
  ca: fs.readFileSync('/path/ca.pem')

https.createServer(options, app).listen(443);

We read in the files with readFileSync .

Then we pass the whole thing into the https.createServer method to create our server.

We still need http.createServer to listen to HTTP requests.

Get Data Passed from a form in Express

We can get the data passed from a form in Express with the body-parser package.

We use the urlencoded middleware that’s included with it.

For instance, we can write:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));'/game', (req, res) => {

Once we have ran urlencoded middleware, it’ll parse form data from POST requests.

extended means we can also parse JSON in the request body.

Then in our route, we can get the data with req.body .

Loop in Jade /Pug Template Engine

We can write a loop with Pug like a JavaScript for loop.

For instance, we write:

- for (let i = 0; i < 10; i) {
  li= array[i]
- }


We can have loops with Pug.

Also, we can read config from a JSON file.

Express can listen to both HTTP and HTTPS requests.

We can transform MongoDB data as we query them.

To add text search capability, we can add an index to speed up the search and use the $search operator.

Leave a Reply

Your email address will not be published. Required fields are marked *