Categories
JavaScript Answers

How to fix Mongoose Schema hasn’t been registered for model error with JavaScript?

To fix Mongoose Schema hasn’t been registered for model error with JavaScript, we require all the model files.

For instance, we write

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/news");
require("./models/Posts");
require("./models/Comments");

to call require to require the Post and Comments schema files to register them.

Categories
JavaScript Answers

How to prevent SQL injection in Node.js?

To prevent SQL injection in Node.js, we use the node-mysql-native library.

For instance, we write

const userId = 5;
const query = connection.query(
  "SELECT * FROM users WHERE id = ?",
  [userId],
  (err, results) => {
    //....
  }
);

to make a select query with the query method.

? is a placeholder for userId.

Therefore, results would be the query result for the

SELECT * FROM users WHERE id = 5

command.

Categories
JavaScript Answers

How to prevent Node.js from exiting while waiting for a callback?

To prevent Node.js from exiting while waiting for a callback, we use the EventEmitter to wait for the event.

For instance, we write

const eventEmitter = new process.EventEmitter();

client.connect((err) => {
  eventEmitter.emit("myEvent", { something: "Bla" });
});

eventEmitter.on("myEvent", (myResult) => {
  process.stdout.write(JSON.stringify(myResult));
});

to create an EventEmitter objbect.

We emit the myEvent event with emit with { something: "Bla" } as the payload.

Then we listen for the myEvent event with on and get the payload from myResult.

Categories
JavaScript Answers

How to create a file only if it doesn’t exist in Node.js?

To create a file only if it doesn’t exist in Node.js, we call the readFile and writeFile methods.

For instance, we write

import * as fs from "fs";

const upsertFile = async (name) => {
  try {
    await fs.promises.readFile(name);
  } catch (error) {
    await fs.promises.writeFile(name, "");
  }
};

to define the upsertFile function.

In it, we call readFile with the file name path to check if the file exists.

If it doesn’t exist, an error is thrown and the catch block is run.

In the catch block, we call writeFile to write the at the name path.

Categories
JavaScript Answers

How to enable cross-origin resource sharing (CORS) in the Express.js framework on Node.js?

To enable cross-origin resource sharing (CORS) in the Express.js framework on Node.js, we add some response headers.

For instance, we write

app.all("/", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

app.get("/", (req, res, next) => {
  // Handle the get for this route
});

app.post("/", (req, res, next) => {
  // Handle the post for this route
});

to call res.header to add the Access-Control-Allow-Origin and Access-Control-Allow-Header response headers to enable CORS.

Then we routes to handle get and post requests from the / URL.