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.

Categories
JavaScript Answers

How to fix Heroku Node.js app deploy failed `error code=H10`?

To fix Heroku Node.js app deploy failed error code=H10, we should not hard code the port for our app.

For instance, we write

app.listen(process.env.PORT || 3000, () => {});

to call listen with the PORT environment variable or 3000 as a fallback to run with the port from the environment variable or on port 3000 as the default.

Categories
JavaScript Answers

How to run Sequelize.js delete query with Node.js?

To run Sequelize.js delete query with Node.js, we call the destroy method.

For instance, we write

Model.destroy({
  where: {
    // criteria
  },
});

to call Model.destroy with an object with the where property set to the criteria for the entries we want to delete.

Categories
JavaScript Answers

How to fix sudo node command not found, but node without sudo is working on EC2?

To fix sudo node command not found, but node without sudo is working on EC2, we add some symlinks as an admin.

We run

sudo ln -s /usr/local/bin/node /usr/bin/node
sudo ln -s /usr/local/lib/node /usr/lib/node
sudo ln -s /usr/local/bin/npm /usr/bin/npm
sudo ln -s /usr/local/bin/node-waf /usr/bin/node-waf

to add the symlinks for the directories for the Node.js paths in our EC2 virtual machine to run Node as root.