Categories
JavaScript Answers

How to use the Mongoose use of select method in Node.js?

Sometimes, we want to use the Mongoose use of select method in Node.js.

In this article, we’ll look at how to use the Mongoose use of select method in Node.js.

How to use the Mongoose use of select method in Node.js?

To use the Mongoose use of select method in Node.js, we can use the find method with the fields we want to return in the results.

For instance, we write

User.find({}, "first last", (err, user) => {
  //...
});

to call User.find with 'first last' to get the User results and return the first and last properties in each result only.

We get the returned query results from the user parameter.

Conclusion

To use the Mongoose use of select method in Node.js, we can use the find method with the fields we want to return in the results.

Categories
JavaScript Answers

How to hash password with Mongoose?

Sometimes, we want to hash password with Mongoose.

In this article, we’ll look at how to hash password with Mongoose.

How to hash password with Mongoose?

To hash password with Mongoose, we can use bcrypt.

For instance, we write

const mongoose = require("mongoose");
const { Schema } = mongoose;
const bcrypt = require("bcrypt");
const SALT_WORK_FACTOR = 10;

const UserSchema = new Schema({
  username: { type: String, required: true, index: { unique: true } },
  password: { type: String, required: true },
});

UserSchema.pre("save", function (next) {
  if (!user.isModified("password")) {
    return next();
  }
  bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
    if (err) return next(err);
    bcrypt.hash(this.password, salt, (err, hash) => {
      if (err) return next(err);
      this.password = hash;
      next();
    });
  });
});

UserSchema.methods.comparePassword = (candidatePassword, cb) => {
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    if (err) {
      return cb(err);
    }
    cb(null, isMatch);
  });
};

module.exports = mongoose.model("User", UserSchema);

to create the User schema with the password field.

When we save the User entry, we call bcrypt.getSalt to generate the salt.

In the genSalt callback, we call bcrypt.hash to hash the password with the salt created.

And then we set this.password to hash and call next to save.

Then we create the comparePassword method by setting UserSchema.methods.comparePassword to a function that calls bcrypt.compare with the candidatePssword and this.password which is current password saved.

We call the cb callback that we call comparePassword with in the function and get whether both passwords match with isMatch.

Then we use it by writing

const testUser = new User({
  username: "abc",
  password: "password123",
});

testUser.save((err) => {
  if (err) throw err;
});

User.findOne({ username: "abc" }, (err, user) => {
  if (err) throw err;

  user.comparePassword("password123", (err, isMatch) => {
    if (err) throw err;
    console.log("password123:", isMatch);
  });

  user.comparePassword("abc", (err, isMatch) => {
    if (err) throw err;
    console.log("abc:", isMatch);
  });
});

to create the testUser User.

And then we call findOneto find the user withusernameset to‘abc’`.

In the findOne callback, we call comparePassword to compare valid and invalid passwords respectively and get whether they match the saved password with isMatch.

Conclusion

To hash password with Mongoose, we can use bcrypt.

Categories
JavaScript Answers

How to set max viewport in Puppeteer?

Sometimes, we want to set max viewport in Puppeteer.

In this article, we’ll look at how to set max viewport in Puppeteer.

How to set max viewport in Puppeteer?

To set max viewport in Puppeteer, we set the defaultViewport option to null.

For instance, we write

const browser = await puppeteer.launch({ defaultViewport: null });

to call puppeteer.luanch with an object that has defaultViewport set to null.

This will make Puppeteer launch with the max viewport resolution instead of 800×600.

Conclusion

To set max viewport in Puppeteer, we set the defaultViewport option to null.

Categories
JavaScript Answers

How to parse XLSX and create JSON with Node.js?

Sometimes, we want to parse XLSX and create JSON with Node.js.

In this article, we’ll look at how to parse XLSX and create JSON with Node.js.

How to parse XLSX and create JSON with Node.js?

To parse XLSX and create JSON with Node.js, we can use the xlsx package.

To install it, we run

npm i xlsx

Then we use it by writing

const XLSX = require("xlsx");
const workbook = XLSX.readFile("Master.xlsx");
const { SheetNames: sheetNames } = workbook;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]]));

to call XLSX.readFile to read the XLSX file from the path in the argument/

Then we get the sheetNames from the workbook object.

Next, we call XLSX.utils.sheet_to_json with the first sheet which we get from workbook.Sheets[sheetNames[0]] return the JSON data converted from the worksheet.

Conclusion

To parse XLSX and create JSON with Node.js, we can use the xlsx package.

Categories
JavaScript Answers

How to get a JSON via HTTP request in Node.js?

Sometimes, we want to get a JSON via HTTP request in Node.js.

In this article, we’ll look at how to get a JSON via HTTP request in Node.js.

How to get a JSON via HTTP request in Node.js?

To get a JSON via HTTP request in Node.js, we can call request with json set to true.

For instance, we write

const options = {
  hostname: "127.0.0.1",
  port: app.get("port"),
  path: "/users",
  method: "GET",
  json: true,
};
request(options, (error, response, body) => {
  console.log(body);
});

to call request with json set to true in the options object to return a JSON response.

Then we get the parsed JSON response body from the body parameter in the callback.

Conclusion

To get a JSON via HTTP request in Node.js, we can call request with json set to true.