Categories
JavaScript Answers

How to query referenced objects in Node MongoDB?

To query referenced objects in Node MongoDB, we use $unwind and $lookup.

For instance, we write

db.Foo.aggregate(
  { $unwind: "$bars" },
  {
    $lookup: {
      from: "bar",
      localField: "bars",
      foreignField: "_id",
      as: "bar",
    },
  },
  {
    $match: {
      "bar.testprop": true,
    },
  }
);

to call aggregate with $unwind to unwind the $bars entries.

And then we look up the testprop field of the bars entries that’s set to true with $match.

Categories
JavaScript Answers

How to hash passwords with Node.js?

To hash passwords with Node.js, we use the bcrypt package.

For instance, we write

import * as bcrypt from "bcrypt";

export const Encrypt = {
  cryptPassword: async (password) => {
    const salt = await bcrypt.genSalt(10);
    const hash = await bcrypt.hash(password, salt);
    return hash;
  },
  comparePassword: async (password, hashPassword) => {
    return await bcrypt.compare(password, hashPassword);
  },
};

to call genSalt to create a salt in the cryptPassword function.

Then we call hash to hash the password with the salt.

And then we call bcrypt.compare to compare the raw password with the hashedPassword with compare.

Categories
JavaScript Answers

How to submit a form with Node Puppeteer?

To submit a form with Node Puppeteer, we call click on the submit button.

For instance, we write

await page.goto("https://www.example.com/login");

await page.type("#username", "username");
await page.type("#password", "password");

await page.click("#submit");

await page.waitForNavigation();

to call goto to go to the page.

Then we call type to enter the values for the inputs with IDs username and password.

And then we call click to click the button with ID submit to submit the form.

Categories
JavaScript Answers

How to fix Cannot find module babel-preset-es2015 error with JavaScript?

To fix Cannot find module babel-preset-es2015 error with JavaScript, we install the @babel/preset-env package.

To install it, we run

npm install --save-dev @babel/preset-env

to install the package.

Then in .babelrc, we write

{
  "presets": ["@babel/preset-env"]
}

to add the preset.

Categories
JavaScript Answers

How to use the async lib – async.foreach with object with Node.js?

To use the async lib – async.foreach with object with Node.js, we call forEach with a callback for each item.

For instance, we write

async.forEach(
  Object.keys(dataObj),
  (item, callback) => {
    console.log(item);
    callback();
  },
  (err) => {
    console.log("iterating done");
  }
);

to call forEach with a callback with the callback parameter that we call in the callback.

The callback in the 2nd argument is called when the async process is done.