Categories
JavaScript Answers

How to use Mongoose to update values in array of objects with Node.js?

To use Mongoose to update values in array of objects with Node.js, we use the $set operator.

For instance, we write

Person.update(
  { "items.id": 2 },
  {
    $set: {
      "items.$.name": "updated",
      "items.$.value": "two updated",
    },
  },
  (err) => {}
);

to call update with an object with $set set to an object with the fields in the item with id 2 to update.

The item being updated is the object in items with id 2.

We update the name and value fields of it.

Categories
JavaScript Answers

How to get the sha1 hash of a string in Node.js?

To get the sha1 hash of a string in Node.js, we use the crypto module.

For instance, we write

const crypto = require("crypto");
const shasum = crypto.createHash("sha1");
shasum.update("foo");
const hash = shasum.digest("hex");

to call createHash to create a hash.

Then we call update to add content to it.

Finally, we call digest with 'hex' to return the hash.

Categories
JavaScript Answers

How to create a Express.js middleware that accepts parameters with JavaScript?

To create a Express.js middleware that accepts parameters with JavaScript, we return a function that takes the arguments we want.

For instance, we write

const hasRole = (role) => {
  return (req, res, next) => {
    if (role !== req.user.role) {
      res.redirect("...");
    } else {
      next();
    }
  };
};

const middlwareHasRoleAdmin = hasRole("admin");

app.get("/hasToBeAdmin", middlwareHasRoleAdmin, (req, res) => {});

to define the hasRole function.

It returns a middleware function that checks the role and either redirects with res.redirect or move to the next middleware with next.

Then we call hasRole with 'admin' to return a middleware with role set to 'admin'.

And we use the middlwareHasRoleAdmin middleware in our /hasToBeAdmin route.

Categories
JavaScript Answers

How to install only “devDependencies” using npm?

To install only "devDependencies" using npm, we use the --only-dev option.

To use it, we run

npm install --only=dev

to use the --only-dev option to only install dev dependencies.

Categories
JavaScript Answers

How to install Node.js as windows service?

To install Node.js as windows service, we use the node-windows package.

For instance, we write

const Service = require("node-windows").Service;

const svc = new Service({
  name: "Hello World",
  description: "The nodejs.org example web server.",
  script: "C:\\path\\to\\helloworld.js",
});

svc.on("install", () => {
  svc.start();
});

svc.install();

to create a Service object with the name, description and the program location.

Then we listen for the install event with on and call start to start the service once it’s installed.

Finally, we call install to install the service.