Categories
Node.js Tips

Node.js Tips — Socket.io, MongoDB and Nested Objects, and Express Issues

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.

Updating a Nested Array with MongoDB

We can update nested arrays with the native MongoDB driver.

To do that, we can use the update method.

We can write:

Model.update({
    "questions.answers._id": "123"
  }, {
    "$push": {
      "questions.answers.$.answeredBy": "success"
    }
  },
  (err, numAffected) => {
    // ...
  }
);

We called update with a few arguments.

The first is the query for the nested array entry to update.

The 2nd is the $push appends a new entry to the questions.answers array with the answeredBy value.

The $ sign is the positional operator, and it’s a placeholder for a single value.

Then the callback has the result after the push operation.

Express Static Relative to Parent Directory

We can use path.join to get the absolute path of the directory that we want to serve as the static folder.

For example, we can write:

const path = require('path');
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, '../public')));

The ../ symbols move one directory level up and we get the public directory from there.

Fix ‘TypeError: Router.use() requires middleware function but got an Object’ Error in Express Apps

To fix this error, we’ve to make sure the routeing module is exported.

For instance, we can write:

users.js

const express = require('express');
const router = express.Router();

router.get('/', (req, res, next) => {
  //Do whatever...
});

module.exports = router;

We have:

module.exports = router;

to export the router .

Then we can use it in another file by writing:

const users = require('./users');

//...
app.use('/users', users);

Socket.io Error Hooking into Express.js

We can incorporate socket.io in our Express app by call the socket.io function.

For instance, we can write:

const express = require('express');
const app = express();
const server = app.listen(port);
const io = require('socket.io')(server);

We just require the socket.io module and call the required function with our server .

server is an http server instance.

Wait for Multiple Async Calls with Node.js

We can use Underscore’s or Lodash’s after method to wait for multiple async calls to be done before calling another function.

For instance, we can write:

const finished = _.after(2, baz);

foo(data, (err) => {
  //...
  finished();
});

bar(data, (err) => {
  //...
  finished();
})

const baz = () => {
  //...
}

The after method returns a finish function that we can call when the async callbacks are called.

Since we want to wait for 2 functions to finish, we pass 2 into after as the first argument.

We call finished in each callback to indicate that it’s finished.

Use Aliases with Node.js’s require Function

We can create aliases for required members by using the destructuring syntax.

For example, we can write:

const { foo: a, bar: b } = require('module');

We import a and b with require .

Then we alias a as foo and b as bar with the destructuring assignment syntax.

Then they’re accessed as foo and bar .

How to Send JavaScript Object with Socket.io

We can send JavaScript objects with socket.io in a few ways.

We can use the send method:

socket.send({ foo: 'b' });

This would convert the object automatically to JSON.

Also, we can use socket.json.send :

socket.json.send({ foo: 'b' });

And we can also use emit :

socket.emit('someEvent', { foo: 'b' });

emit emits an event with name someEvent and an object in the 2nd argument.

Get Error Status Code from HTTP GET

To get the error code for a GET request made with the http module, we can get it from the statusCode property of res .

For instance, we can write:

const https = require('https');

https.get('https://example.com/error', (res) => {
  console.log(res.statusCode);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
})
.on('error', function(e) {
  console.error(e);
});

The status code is in the res.statusCode property to get the status code.

Conclusion

We can use update to update a nested array with MongoDB.

The status code of a request made with http is in the statusCode property.

We can send objects with socket.io.

Static folders should be served with absolute paths with Express.

We can use after to wait for multiple async calls to complete before calling another function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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