Categories
JavaScript Answers

How to add REST endpoints with Express.js nested router?

Sometimes, we want to add REST endpoints with Express.js nested router.

In this article, we’ll look at how to add REST endpoints with Express.js nested router.

How to add REST endpoints with Express.js nested router?

To add REST endpoints with Express.js nested router, we should make sure our route URL and request methods follow the REST convention.

For instance we write

const express = require('express');
const app = express();

const userRouter = express.Router();
const itemRouter = express.Router({
  mergeParams: true
});

userRouter.use('/:userId/items', itemRouter);

userRouter.route('/')
  .get((req, res) => {
    res.status(200)
      .send('hello users');
  });

userRouter.route('/:userId')
  .get((req, res) => {
    res.status(200)
      .send(req.params.userId);
  });

itemRouter.route('/')
  .get((req, res) => {
    res.status(200)
      .send(`items ${req.params.userId}`);
  });

itemRouter.route('/:itemId')
  .get((req, res) => {
    res.status(200)
      .send(`item ${req.params.itemId} user ${req.params.userId}`);
  });

app.use('/user', userRouter);

app.listen(3000);

to nest itemRouter in userRoute.

We have

userRouter.use('/:userId/items', itemRouter);

to nest itemRouter in userRouter.

We set mergeParams to true so that the URL from userRouter is combined with the URLs of the routes with itemRouter.

As a result, we get the following results when the following requests are made:

  • GET /user -> hello user
  • GET /user/5 -> 5
  • GET /user/5/items -> items 5
  • GET /user/5/items/6 -> item 6 user 5

Conclusion

To add REST endpoints with Express.js nested router, we should make sure our route URL and request methods follow the REST convention.

Categories
JavaScript Answers

How to fix the ‘mongoError: Topology was destroyed’ error with Mongoose?

Sometimes, we want to fix the ‘mongoError: Topology was destroyed’ error with Mongoose.

In this article, we’ll look at how to fix the ‘mongoError: Topology was destroyed’ error with Mongoose.

How to fix the ‘mongoError: Topology was destroyed’ error with Mongoose?

To fix the ‘mongoError: Topology was destroyed’ error with Mongoose, we should make sure our connection to the MongoDB server isn’t interrupted.

For instance, we write

const options = {
  server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
  replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};
mongoose.connect(secrets.db, options);

to call mongoose.connect with the options.

We set the server‘s keepAlive option to 1 to keep the connection alive.

And we set connectTimeoutMS to 30000 milliseconds to extend the connection attempt duration before timing out.

We set the same options for the replica set by setting replset to the same options.

Conclusion

To fix the ‘mongoError: Topology was destroyed’ error with Mongoose, we should make sure our connection to the MongoDB server isn’t interrupted.

Categories
JavaScript Answers

How to properly close Mongoose’s connection once it’s done ?

Sometimes, we want to properly close Mongoose’s connection once it’s done.

In this article, we’ll look at how to properly close Mongoose’s connection once it’s done.

How to properly close Mongoose’s connection once it’s done?

To properly close Mongoose’s connection once it’s done, we can use the mongoose.disconnect method.

For instance, we write

const db = mongoose.connect('mongodb://localhost:27017/somedb');

// ...

db.disconnect();

to call mongoose.connect with the database URL to connect to the database.

And then we call disconnect on the db handle to disconnect the database connection once we’re done.

Conclusion

To properly close Mongoose’s connection once it’s done, we can use the mongoose.disconnect method.

Categories
JavaScript Answers

How to add “All Rights Reserved” license in package.json?

Sometimes, we want to add "All Rights Reserved" license in package.json.

In this article, we’ll look at how to add "All Rights Reserved" license in package.json.

How to add "All Rights Reserved" license in package.json?

To add "All Rights Reserved" license in package.json, we add

{
  "license": "UNLICENSED"
}

into package.json

This will let us denying grant rights to use a private or unpublished package under any terms.

Conclusion

To add "All Rights Reserved" license in package.json, we add

{
  "license": "UNLICENSED"
}
Categories
JavaScript Answers

How to select a specific field with Mongoose find?

Sometimes, we want to select a specific field with Mongoose find.

In this article, we’ll look at how to select a specific field with Mongoose find.

How to select a specific field with Mongoose find?

To select a specific field with Mongoose find, we can use the schema find method with the field we want to select.

For instance, we write

dbSchemas.SomeValue.find({}, 'name', (err, someValue) => {
  if (err) {
    return
  }
  console.log(someValue);
});

to call dbSchemas.SomeValue.find to select the 'name' property.

Then someValue would be the value of the name property.

Conclusion

To select a specific field with Mongoose find, we can use the schema find method with the field we want to select.