Categories
JavaScript Answers

How to pass variable from jade template file to a script file with JavaScript?

To pass variable from jade template file to a script file with JavaScript, we pass in the variable to the template with render.

For instance, in our Jade template, we write

script.
  loginName="#{login}";

Then we write

exports.index = (req, res) => {
  res.render("index", { layout: false, login: req.session.login });
};

to call res.render with an object with the login property set to the value we want to pass to the Jade template.

Categories
JavaScript Answers

How to clone a JavaScript ES6 class instance?

To clone a JavaScript ES6 class instance, we use a few object methods.

For instance, we write

const clone = Object.assign(Object.create(Object.getPrototypeOf(orig)), orig);

to get the prototype of the orig object with Object.getPrototypeOf.

Then we create a new object from the prototype with Object.create.

Then we call Object.assign to make a copy of the object we created and return it.

Categories
JavaScript Answers

How to require file as string with Node.js?

To require file as string with Node.js, we call readFileSync.

For instance, we write

import fs from "fs";
import path from "path";

const css = fs.readFileSync(path.resolve(__dirname, "email.css"), "utf8");

to read the email.css file into a string with the readFileSync method.

Categories
JavaScript Answers

How to fix Unknown column ‘*.createdAt’ in ‘field list’ error with Node.js Sequelize?

To fix Unknown column ‘*.createdAt’ in ‘field list’ error with Node.js Sequelize, we add a model with the createdAt field.

For instance, we write

const users = sequelize.define("users", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
  },
  createdAt: {
    field: "created_at",
    type: Sequelize.DATE,
  },
  updatedAt: {
    field: "updated_at",
    type: Sequelize.DATE,
  },
  //...
});

to add the createdAt field to the users model and map it toi the created_at date field.

Categories
JavaScript Answers

How to do batch insert with Node.js MongoDB Mongoose?

To do batch insert with Node.js MongoDB Mongoose, we call the insertMany method.

For instance, we write

const rawDocuments = [
  /* ... */
];

const mongooseDocuments = await Book.insertMany(rawDocuments);

to call the insertMany method in the Book schemas to insert the rawDocuments into the database.