Categories
JavaScript Answers

How to save multiple documents concurrently in Mongoose and Node.js?

To save multiple documents concurrently in Mongoose and Node.js, we call the create method.

For instance, we write

const array = [{ type: "jelly bean" }, { type: "snickers" }];
Candy.create(array, (err, jellybean, snickers) => {
  if (err) {
    //...
  }
});

to call the create method with the array to write the entries into the collection.

And then we get the written entries from the parameters after err.

err is the error if there is any.

Categories
JavaScript Answers

How to clear console on Node.js on windows?

To clear console on Node.js on windows, we call the proces.stdout.write method.

For instance, we write

process.stdout.write('\033c');

to call write with '\033c' to clear the console.

Categories
JavaScript Answers

How to include external .js file in Node.js app?

To include external .js file in Node.js app, we create a module.

For instance, we write

const make = (Schema, mongoose) => {
  CarSchema = new Schema({
    brand: String,
    type: String,
  });
  mongoose.model("Car", CarSchema);
};

module.exports.make = make;

in car.js to export the make function.

Then we use it by writing

const app = require("express").createServer();
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

require("./models/car.js").make(Schema, mongoose);

We call require to require the car.js file and call make from the returned object.

Categories
JavaScript Answers

How to fix Babel unexpected token import when running mocha tests with JavaScript?

To fix Babel unexpected token import when running mocha tests with JavaScript, we add the @babel/preset-env library.

To install it, we run

npm install @babel/preset-env --save-dev

Then in the .babelrc file, we add

{
  "presets": ["@babel/preset-env"]
}

to add the Babel preset to clear the syntax error.

Categories
JavaScript Answers

How to fix Node js Error: Protocol “https:” not supported. Expected “http:”?

To fix Node js Error: Protocol "https:" not supported. Expected "http:", we use https.get method.

For instance, we write

const http = require("http");
const https = require("https");
const url = new URL("https://www.example.com");
const client = url.protocol == "https:" ? https : client;
const req = client.get(url, (res) => {
  console.log(res);
});

to get the client according to the url‘s protocol.

We use the https client if it’s https and http if it’s http.

Then we call get with the client for the right protocol to make the get request.