Categories
JavaScript Answers

How to install the exact package version specified in package.json with Node.js npm install?

To install the exact package version specified in package.json with Node.js npm install, we use the --save-exact option.

For instance, we run

npm install --save --save-exact react

to install the exact version of the react package listed in package.json with --save-exact.

Categories
JavaScript Answers

How to get the objectID after saving an object in Mongoose and JavaScript?

To get the objectID after saving an object in Mongoose and JavaScript, we get the saved document from the returned promise.

For instance, we write

const gnr = new Band({
  name: "Band",
  members: ["Axl", "Slash"],
});

const doc = await gnr.save();

to create a new Band.

And then we call save to return a promise with the saved document.

We use await to get the document from the promise.

Categories
JavaScript Answers

How to use multiple parameters in URL in Node.js Express?

To use multiple parameters in URL in Node.js Express, we add multiple parameter placeholders.

For instance, we write

app.get("/fruit/:fruitName/:fruitColor", (req, res) => {
  const data = {
    fruit: {
      apple: req.params.fruitName,
      color: req.params.fruitColor,
    },
  };

  send.json(data);
});

to add the fruitName and fruitColor URL placeholders for the get route.

Then we get their values from the req.params object.

Categories
JavaScript Answers

How to start a Node.js server as a daemon process?

To start a Node.js server as a daemon process, we use the forever package.

For instance, we run

npm install -g forever

to install forever globally.

Then we run it by running

forever start server.js

We run server.js as a daemon with forever start.

Categories
JavaScript Answers

How to fix “Cannot find module ‘ts-node/register'” error with JavaScript?

To fix "Cannot find module ‘ts-node/register’" error with JavaScript, we install the ts-node package.

To install it, we run

npm install ts-node --save-dev

to save the ts-node package as a dev dependency.