Categories
JavaScript Answers

How to see the SQL generated by Node Sequelize.js?

To see the SQL generated by Node Sequelize.js,. we set the logging option.

For instance, we write

const sequelize = new Sequelize("database", "username", "password", {
  logging: console.log,
});

to set the logging property to log with console.log.

We can also write

const sequelize = new Sequelize("database", "username", "password", {
  logging: (str) => {
    // do your own logging
  },
});

to log with our own logging function.

Categories
JavaScript Answers

How to redirect to URL with Node.js?

To redirect to URL with Node.js, we use the res.redirect method.

For instance, we write

res.redirect("your/404/path.html");

to call res.redirect with the path to redirect to with Express.

Categories
JavaScript Answers

How to add a single routing handler for multiple routes in a single line with Node.js Express.js?

To add a single routing handler for multiple routes in a single line with Node.js Express.js, we call the route method with an array of routes.

For instance, we write

app.get(
  [
    "/test",
    "/alternative",
    "/bar*",
    "/foo/:farcus/",
    "/hoop(|la|lapoo|lul)/poo",
  ],
  (request, response) => {}
);

to create a get route handler that accepts requests from the URLs listed in the array.

Categories
JavaScript Answers

How to pipe a stream to s3.upload() with Node.js?

To pipe a stream to s3.upload() with Node.js, we call the stream.PassThrough constructor.

For instance, we write

const uploadFromStream = (s3) => {
  const pass = new stream.PassThrough();
  const params = { Bucket: BUCKET, Key: KEY, Body: pass };
  s3.upload(params, (err, data) => {
    console.log(err, data);
  });

  return pass;
};

inputStream.pipe(uploadFromStream(s3));

to define the uploadFromStream function.

In it, we create a PassThrough object.

Then we call upload with the params object to upload the stream data.

Next, we call pipe with the PassThrough object returned by uploadFromStream to upload the inputStream data.

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.