Categories
JavaScript Answers

How to fix req.user Undefined with Node, Express and Passport?

To fix req.user Undefined with Node, Express and Passport, we add the Passport middlewares.

For instance, we write

app.use(session({ secret: "anything" }));
app.use(passport.initialize());
app.use(passport.session());

to add Passport into our Express app by calling app.use with the middlewares returned by passport.initialize and passport.session.

Categories
JavaScript Answers

How to add Where statement with date with Node Sequelize?

To add Where statement with date with Node Sequelize, we use operator properties.

For instance, we write

const { Op } = require("sequelize");

model.findAll({
  where: {
    start_datetime: {
      [Op.gte]: moment().subtract(7, "days").toDate(),
    },
  },
});

to call findAll to look for the entries with start_datetime bigger than or equal to 7 days before today.

We get the date with moment().subtract(7, "days").toDate().

Categories
JavaScript Answers

How to add optional splat param with Node Express.js routing?

To add optional splat param with Node Express.js routing, we use a question mark.

For instance, we write

router.get("/path/:id*?", (req, res, next) => {
  res.render("page", { title: req.params.id });
});

to call get to with the path of the route.

We make id an option parameter with ?.

And we get the id value with req.params.id.

Categories
JavaScript Answers

How to fix the ‘Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused’ error with Node MongoDB?

To fix the ‘Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused’ error with Node MongoDB, we remove the Mongo lock file.

To do this, we run

sudo rm /var/lib/mongodb/mongod.lock
sudo service mongod restart

to remove the mongod.lock file with rm.

Then we restart the Mongo server with service mongod restart.

Categories
JavaScript Answers

How to wait until an element is visible with JavaScript Puppeteer?

To wait until an element is visible with JavaScript Puppeteer, we call waitForSelector.

For instance, we write

const puppeteer = require("puppeteer");

const broswer = await puppeteer.launch();
const page = await browser.newPage();
await page.waitForSelector("#myId");
browser.close();

to call launch to launch the browser.

We call awaitForSelector to wait for the element with ID myId to show.