Categories
JavaScript Answers

How to fix MongoNetworkError: failed to connect to server [localhost:27017] on first connect with Node MongoDB?

To fix MongoNetworkError: failed to connect to server [localhost:27017] on first connect with Node MongoDB, we should make sure we’re connecting to a reachable Mongo server.

For instance, we write

await mongoose.connect("mongodb://localhost/testdb");

to call mongoose.connect to connect to the testdb database on localhost.

The error shouldn’t be thrown if it’s reachable.

Categories
JavaScript Answers

How to Add, Delete new Columns in Node Sequelize CLI?

To Add, Delete new Columns in Node Sequelize CLI, we create a migration file.

For instance, we run

$ sequelize migration:create --name name_of_your_migration

to create a migration.

Then we write

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn("Todo", "completed", Sequelize.BOOLEAN);
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.removeColumn("Todo", "completed");
  },
};

to call addColumn to add a column with the table name, column name, and data type.

We call removeColumn with the table name and column name to remove it.

Then we run

$ sequelize db:migrate

to call the up function in the migration file.

Categories
JavaScript Answers

How to get the width and height of an image in Node.js?

To get the width and height of an image in Node.js, we use the image-size package.

For instance, we write

const sizeOf = require("image-size");

sizeOf("images/funny-cats.png", (err, dimensions) => {
  console.log(dimensions.width, dimensions.height);
});

to call the sizeOf function to read the images/funny-cats.png image.

And we get the width and height from the dimensions parameter in the callback.

Categories
JavaScript Answers

How to fix Date.now().toISOString() throwing error “not a function” with JavaScript?

To fix Date.now().toISOString() throwing error "not a function" with JavaScript, we call toISOString on a date object.

For instance, we write

const now = new Date();
const isoString = now.toISOString();

to create a new Date object now.

Then we call now.toISOString to return the datetime string from the date.

Categories
JavaScript Answers

How to convert a directory structure in the filesystem to JSON with Node.js?

To convert a directory structure in the filesystem to JSON with Node.js, we use the directory-tree package.

To install it, we run

npm i directory-tree

Then we use it by writing

const directoryTree = require("directory-tree");

const tree = directoryTree("/some/path");
const filteredTree = directoryTree("/some/path", [".jpg", ".png"]);

to call directoryTree to return an object of the directory structure with the /some/path folder as root.

We can also call it with a 2nd argument to filter the items by extension.