Categories
JavaScript Answers

How to read value from console interactively with Node.js?

Sometimes, we want to read value from console interactively with Node.js.

In this article, we’ll look at how to read value from console interactively with Node.js.

How to read value from console interactively with Node.js?

To read value from console interactively with Node.js, we can use the process.openStdin method.

For instance, we write

const stdin = process.openStdin();

stdin.addListener("data", (d) => {
  console.log(d.toString().trim())
});

to call process.openStdin to accept interactive input from the console.

Then we call stdin.addListener with 'data and a callback to get the entered data d.

The data event is emitted when input is entered.

In the callback, we convert the input data to a string with toString and trim the starting and ending whitespaces with trim.

Conclusion

To read value from console interactively with Node.js, we can use the process.openStdin method.

Categories
JavaScript Answers

How to generate an ObjectId with Mongoose?

Sometimes, we want to generate an ObjectId with Mongoose.

In this article, we’ll look at how to generate an ObjectId with Mongoose.

How to generate an ObjectId with Mongoose?

To generate an ObjectId with Mongoose, we can use the mongoose.Types.ObjectId constructor.

For instance, we write

const mongoose = require('mongoose');
const id = new mongoose.Types.ObjectId();

to create an ObjectId with mongoose.Types.ObjectId and assign it to id.

We don’t need new before mongoose.Types.ObjectId before Mongoose v6.

Conclusion

To generate an ObjectId with Mongoose, we can use the mongoose.Types.ObjectId constructor.

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.