Node: Problems & Solutions - Part 1 of 3 (45% through course)

Here are some problems and solutions for first part of Node course.

I have now posted three Parts. This is Part 1 almost half way through. Part 2 is rest of course excluding deployment, which is Part 3. Hope this is useful. (I am running Windows 10, using vscode and latest npm packages (Jan-Mar 2022).

Building RESTful APIs Using Express: Handling PUT request: got error “Class constructors cannot be invoked without ‘new’”. Solved by changing this line

  return Joi.ValidationError(course, schema);

to this:

  const result = new Joi.ValidationError(course, schema);
  return result;

Express- Advanced Topics :
Configuration: course said use SET for env variables in Windows. But if using Hyper terminal then use EXPORT not SET to create env variables.
Templating Engines: Mosh said when building RESTful services you dont really need a view engine or a templating engine and he was just covering them for completeness!?? He did NOT say why you dont really need them? Perhaps will find out later in course.
Database Integration: gave error cant find module ‘./courses’ because it is in sub folder ‘./routes/courses’. Mosh picked that up later.

CRUD Operations Using Mongoose:
Connecting to Mongodb. - i did NOT connect. Gave no error. When running nodemon, says “clean exit”. When running node index.js shows nothing. Solved by changing code to:

const mongoose = require("mongoose");
const myDB = "playground"; // default database
const mongoDB = "mongodb://localhost:27017/" + myDB;
mongoose
  .connect(mongoDB, { useNewUrlParser: true })
  .then(() => cl("Connected to Mongodb..."))
  .catch((err) => console.error("Cant connect to database ...", err));

Then I realised Mosh’s code didnt specify port:27017 so that might have solved problem also.

Ex 14: mongoimport : the command line didnt work because since Mongodb 4.4 mongoimport is release separately from Mongodb Server and you have to install MongoTools now to get it. Here is a link:
Mongo Tools

PLEASE NOTE: the text file Mosh provided has _ids for each document and these are strings. It should NOT have these. Do yourself a big favour and REMOVE the “”_id":“5a68fdc3615eda645bc6bdec”," from each item in the JSON file. When you IMPORT, the db will create the ids as object ids and NOT strings. This WILL cause an error if you import these string Ids.

If you installed Mongo Compass then you can create the database, select it and then import the json file with the data for the exercises from within Compass - you dont need the command line.

Mongo Data Validations: Async Validators
This gave me two errors. Document must have an _id before saving and callback is not a function.
Solution to “must have an _id before saving”: I had added _id: String to Schema to solve an earlier problem, but then realised the JSON file should NOT have _ids as the db will create these when imported. So, I removed them, imported and then that error disappeared.
Solution to “callback is not a function”. This took hours to solve and mongodb documentation didnt help. The “IsAsync: true” didnt seem to do anything and the setTimeout() didnt seem to wait either. Long story short, here is my solution: Add this delay function to top of index.js. This will be called by Tags validate, shown below.

const delay = (n) => {
  return new Promise(function (resolve) {
    setTimeout(resolve, n * 1000);
  });
};
tags: {
    type: Array,
    validate: {
      //isAsync: true,
      validator: async function (v) {
        await delay(3);
        const result = v && v.length > 0;
        return result;
      },
      message: "A Document should have at least one tag!",
    },
  },

If you call the createCourse() functon with tags: []; (empty) then you will get the expected error message and if tags: ['contains something"] then the record will be added.

By the way, I have used a function cl() that I created, too tired of writing console.log. That function is:

const cl = (...args) => console.log(...args);

I put another post with solutions to Exercises 1-3 in this section, reusing function rather than duplicating code for each exercise.

Hope this helps someone out there. I will post on the second half of the course soon.

1 Like