Categories
Node.js Tips

Node.js Tips — Mongoose Relationships, Body Parser, and Reading and Writing Files

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

Disable Express BodyParser for File Uploads

We can bypass body-parser by setting the value of the body.parse('multipart/form-data') function to a different value.

For instance, we can write:

const express = require('express');
const bodyParser = express.bodyParser;

bodyParser.parse('multipart/form-data') = (req, options, next) => {
  next();
}

We set a new value to the body.parse('multipart/form-data') function to do nothing and just call next .

Then no parsing will be done when multipart/form-data data types are encountered.

A better way is to not use bodyParser directory.

Instead, we can just use it to parse the data type we want by writing:

const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

We call the json and urlencoded methods to only parse JSON and URL encoded data.

Node.js — Creating Relationships with Mongoose

We can create relationships with Mongoose by using the ref property.

For instance, we can write:

const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const PersonSchema = new Schema({
  name : String
})

const AddressSchema = new Schema({
  street: String
  person: { type: ObjectId, ref: 'PersonSchema' }
})

In AddressSchema , we set the ref property to the string of the schema name for PersonSchema .

Then we can use it by writing:

const person = new PersonSchema({ name: 'james' });
person.save();

const address = new AddressSchema({
  phone: '123 A St.',
  person: person._id
});
address.save();

We create the person and address , which is related to person .

The person._id if the object ID for the person which we want to reference in address .

Then we can get the address when we query PersonSchema buy writing:

PersonSchema
  .findOne({})
  .populate('address')
  .exec((err, address) => {
    //...
  })

We query the PersonSchema with findOne , then call populate to get the address from the person.

Looping Through Files in a Folder Node.js

We can loop through files in a folder in Node apps by using the opendir method.

For instance, we can write:

const fs = require('fs')

const listFiles = async (path) => {
  const dir = await fs.promises.opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
}

listFiles('.').catch(console.error)

We use the promise version of the opendir method.

The path is the path to the folder.

Then we use the for-await-of loop to read the entry’s name property to log their name.

Since an async function returns a promise, we can use catch to handle errors when we read the directory’s entries.

We can also read a directory’s entries synchronously.

For instance, we can write:

const fs = require('fs');

const dir = fs.opendirSync('.');
let dirent;
while ((dirent = dir.readSync()) !== null) {
  console.log(dirent.name)
}
dir.closeSync();

We call openDirSync to read the entries with the given path.

Then we use the while loop to read each entry with readSync .

Then we close the handle with closeSync .

Checking if writeFileSync Successfully Wrote the File

writeFileSync doesn’t return anything, so we won’t know whether the file is successfully written.

Instead, we can use the async version, which takes a callback that brings us the error if there’s an error.

For instance, we can write:

fs.exists(file, (exists) => {
  if (exists) {
    fs.writeFiles(file, content, 'utf-8', (err) => {
      if (err) {
        console.log("failed to save");
      } else {
        console.log("success");
      }
  } else {
    console.log('file not found');
  }
}

We check if the exists. If it does exist, then we write what we want to it.

file is the file path. content is the content that we want to write.

'utf-8' is the encoding.

err is the error that’s encountered when the file failed to save.

Otherwise, we don’t do anything.

Conclusion

We can use parts of the body-parser package to parse the request payload we want.

Mongoose can create schemas with relationships.

We can loop through folders with various methods.

Also, we can check if a file exists before we write to them.

writeFileSync doesn’t guarantee that file writing operations succeed.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *