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.

Categories
JavaScript Answers

How to make connection to Postgres via Node.js?

To make connection to Postgres via Node.js, we use the Pool constructor.

For instance, we write

const { Pool } = require("pg");
const config = {
  user: "foo",
  database: "my_db",
  password: "secret",
  host: "localhost",
  port: 5432,
  max: 10,
  idleTimeoutMillis: 30000,
};
const pool = new Pool(config);
pool.on("error", (err, client) => {
  console.error("idle client error", err.message, err.stack);
});
pool.query("SELECT $1::int AS number", ["2"], (err, res) => {
  if (err) {
    return console.error("error running query", err);
  }
  console.log("number:", res.rows[0].number);
});

to call Pool with the connection config.

Then we call query to make a database query.

We get the results from the res parameter in the callback.