Categories
JavaScript Answers

How to fix error installing bcrypt with npm?

To fix error installing bcrypt with npm, we install the bcryptjs module.

For instance, we run

npm install --save bcryptjs && npm uninstall --save bcrypt

to install the bcryptjs module and uninstall the bcrypt module.

Categories
JavaScript Answers

How to get city name from a latitude and longitude point with JavaScript?

To get city name from a latitude and longitude point with JavaScript, we use the MapQuest API.

For instance, we write

const fetchLocationName = async (lat, lng) => {
  const response = await fetch(
    "https://www.mapquestapi.com/geocoding/v1/reverse?key=API-Key&location=" +
      lat +
      "%2C" +
      lng +
      "&outFormat=json&thumbMaps=false"
  );
  const responseJson = await response.json();
  console.log(JSON.stringify(responseJson));
};

to make a get request to the MapQuest reverse geocoding URL with fetch with the lat latitude and lng longitude.

Then we call json to get the JSON response body from response.

Categories
JavaScript Answers

How to combine two OR-queries with AND in Mongoose and JavaScript?

To combine two OR-queries with AND in Mongoose and JavaScript, we use $and and $or together.

For instance, we write

Test.find(
  {
    $and: [{ $or: [{ a: 1 }, { b: 1 }] }, { $or: [{ c: 1 }, { d: 1 }] }],
  },
  (err, results) => {
    //...
  }
);

to call find with an object with the $and property set to an array with 2 objects with $or properties.

The 2 $or queries will then be combined with the $and query.

We get the returned results from results.

Categories
JavaScript Answers

How to wait some asynchronous tasks complete in JavaScript?

To wait some asynchronous tasks complete in JavaScript, we call the async.each method.

For instance, we write

const async = require("async");

async.each(
  ["aaa", "bbb", "ccc"],
  (name, callback) => {
    conn.collection(name).drop(callback);
  },
  (err) => {
    if (err) {
      return console.log(err);
    }
    console.log("all dropped");
  }
);

to call async.each to with an input array.

The first callback calls some async function with each item in the array.

And the 2nd callback is an error handler callback.

Categories
JavaScript Answers

How to log all queries that Mongoose fire in the application with JavaScript?

To log all queries that Mongoose fire in the application with JavaScript, we call the set method.

For instance, we write

mongoose.set("debug", (collectionName, method, query, doc) => {
  console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});

to call set with a callback to log the values from the query.

We log the collectionName collection, method that’s called, the query made, and the doc results returned.