Categories
JavaScript Answers

How to fix Uncaught TypeError: Object.values is not a function JavaScript?

To fix Uncaught TypeError: Object.values is not a function JavaScript, we can use Object.keys instead.

For instance, we write

const vals = Object.keys(countries).map((key) => {
  return countries[key];
});

to get the keys from the countries object with Object.keys.

Then we call map with a callback to get the value from each key in countries and return the array of values.

Categories
JavaScript Answers

How to fix Mongoose: CastError: Cast to ObjectId failed for value “[object Object]” at path “_id” with Node.js?

To fix Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id" with Node.js, we make sure we’re casting a valid value to an object ID.

For instance, we write

const mongoose = require("mongoose");

console.log(mongoose.Types.ObjectId.isValid("53cb6b9b4f4ddef1ad47f943"));
console.log(mongoose.Types.ObjectId.isValid("whatever"));

to use the mongoose.Types.ObjectId.isValid to check if the value we’re trying to cast to an object ID is a valid value.

The first console log should log true since it’s a valid object ID value.

And the 2nd one logs false since it’s not a valid object ID value.

Categories
JavaScript Answers

How to parse Query String in Node.js?

To parse Query String in Node.js, we use the querystring module.

For instance, we write

const http = require("http");
const queryString = require("querystring");

http
  .createServer((oRequest, oResponse) => {
    let oQueryParams;
    if (oRequest.url.indexOf("?") >= 0) {
      oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ""));
      console.log(oQueryParams);
    }

    oResponse.writeHead(200, { "Content-Type": "text/plain" });
    oResponse.end("Hello world.");
  })
  .listen(3000, "127.0.0.1");

to call queryString.parse to parse the request URL that we got from oRequest.url.

We get pack an object with the keys and values of the query string.

Categories
JavaScript Answers

How to go back 1 folder level with __dirname with Node.js?

To go back 1 folder level with __dirname with Node.js, we use the path.join method.

For instance, we write

const path = require("path");
const configFile = path.join(__dirname, "../test/karma.conf.js");

to call path.join with __dirname and a string with the path one level above __dirname with ../ to return a path one level above __dirname.

Categories
JavaScript Answers

How to pass execution arguments to app using Node.js PM2?

To pass execution arguments to app using Node.js PM2, we use the --

For instance, we run

pm2 start app.js -- --prod --second-arg --third-arg

to start app.js with start.

And then we pass in the arguments after --.