Importing Development Data | Lecture 92 | Node.JS 🔥

The Coding Classroom
27 Sept 202315:41

Summary

TLDRIn this instructional video, the presenter takes a break from API development to demonstrate a script that imports tour data from a JSON file into a MongoDB database. The script operates independently from the express application and includes steps to connect to the database, read the JSON file, and utilize the tour model for data import. Additionally, the video covers command-line interaction, allowing users to run the script with options to import or delete data. The presenter addresses potential validation errors and concludes with a successful data import, setting the stage for future API enhancements.

Takeaways

  • 🛠️ The script's purpose is to import tour data from a JSON file into a MongoDB database, separate from the main Express application.
  • 📝 The script is created in a 'data' folder and named 'importDevData.js', emphasizing its standalone nature.
  • 📚 Mongoose is required for database interactions, and environment variables are needed for database connection details.
  • 🔌 The script requires the file system module 'fs' to read the JSON file and the 'tour' model to interact with the database.
  • 📖 The JSON file is read synchronously with a specified encoding of 'utf eight'.
  • 🔍 An async function is used to import data into the database, utilizing 'tour.create' to handle an array of objects.
  • 🗑️ There's a function to delete all data from the MongoDB collection using 'deleteMany', a method provided by Mongoose.
  • 📋 The script can be run with command-line options to either import or delete data, demonstrated by checking 'process.argv'.
  • 🔄 The script includes error handling with try-catch blocks to log issues during data import or deletion.
  • 🚫 Validation errors are encountered due to incomplete data in the JSON file, highlighting the importance of data integrity.
  • 🔚 The script exits the process after completing its task using 'process.exit', ensuring the script doesn't continue running unnecessarily.

Q & A

  • What is the purpose of the script mentioned in the video?

    -The script's purpose is to import tour data from a JSON file into a MongoDB database, which is a standalone task separate from the main Express application.

  • Why was the decision made to include the script-building exercise in the course?

    -The script-building exercise was included because it was considered a nice little exercise that adds value to the course, despite the possibility of just providing the script in the starter files.

  • What does the script need to perform its task?

    -The script requires mongoose for database interaction, the .env package for environment variables, the file system module to read the JSON file, and the tour model to write the data into the database.

  • How does the script handle reading the JSON file?

    -The script uses the synchronous version of `fs.readFile` to read the JSON file named 'toursSimple.json' and specifies the encoding as 'utf eight'.

  • What is the significance of the 'importData' function in the script?

    -The 'importData' function is an asynchronous function that imports data into the database by using the 'tour.create' method with an array of JavaScript objects obtained from parsing the JSON file.

  • How can the script handle the deletion of existing data in the database?

    -The script includes a function to delete all data from the database using the 'delete many' function of the tour model, which removes all documents in the tours collection.

  • What is the role of 'process.argv' in the script?

    -'process.argv' is used to interact with the command line, allowing the script to accept arguments that determine whether to import or delete data from the database.

  • Why is the 'process.exit' function used in the script?

    -The 'process.exit' function is used to stop the script execution after completing the import or delete operation, as it is a small standalone script and not part of a larger application.

  • What issue occurred when the script was first run to import data?

    -The script encountered validation errors because the JSON file contained some tours with incomplete data, specifically missing 'group size' and other required fields.

  • How can the script be improved to avoid importing incomplete data?

    -The script can be improved by adding checks to ensure that all required fields are present in the JSON data before attempting to import it into the database.

  • What is the final step in the script after successfully importing the data?

    -The final step is to log a success message to the console indicating that the data has been successfully loaded into the database and then exit the process using 'process.exit'.

Outlines

00:00

🛠️ Building a Data Import Script for MongoDB

The script's purpose is to import tour data from a JSON file into a MongoDB database, operating independently from the main Express application. The author considers whether to include this as an exercise or provide it pre-built but decides to include it for educational value. The process involves creating a script in the data folder named 'importDevData.js', setting up necessary modules including mongoose for database connection, the 'fs' module for file system access, and the tour model for data insertion. The script reads a JSON file synchronously and includes error handling. It demonstrates the use of 'tour.create' to insert data into the database, converting JSON data to JavaScript objects with 'JSON.parse'.

05:01

🗑️ Deleting Existing Data and Command Line Interaction

The script also features a function to delete all existing data from the database using 'deleteMany', which removes all documents in the collection. The author discusses the use of 'process.argv' to interact with the command line, allowing the script to be run with different options to either import or delete data. The script is tested by running it with node and observing the output of 'console.log(process.argv)'. Adjustments are made to correctly specify file paths using the 'dirname' variable, and the script is enhanced to handle command line arguments for importing or deleting data.

10:03

🔧 Refining the Script with Command Line Options

The script is refined to check command line arguments and execute the appropriate function based on the user's input. If the '--import' option is provided, the import function is executed; if the '--delete' option is used, the delete function is triggered. The author demonstrates running the script with the delete option, which successfully removes all data from the database, and then attempts to run it with the import option. However, an error occurs due to validation errors related to missing 'group size' in the tour data. The author investigates and identifies that the issue stems from incomplete data entries added in a previous section of the course.

15:04

🎉 Successful Data Import and Wrapping Up

After addressing the data validation issues by removing incomplete tour entries, the author successfully imports the data into the database using the script with the import option. The script includes 'process.exit' to terminate the process after completing the operation. The author concludes the tutorial by expressing satisfaction with the script's functionality and looks forward to the next video, where the focus will be on enhancing the API with new features using the imported data.

Mindmap

Keywords

💡API

API stands for Application Programming Interface, which is a set of rules and protocols for building and interacting with software applications. In the context of the video, the script is being developed to interact with an API, specifically for importing tour data into a MongoDB database. The script is part of a larger project to build an Express application, which is a type of server-side software framework that can be used to create APIs.

💡JSON

JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write, and for machines to parse and generate. In the video, the script is designed to import data from a JSON file, which contains the tour information that needs to be loaded into the MongoDB database.

💡MongoDB

MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format. The script mentioned in the video is used to interact with a MongoDB database, specifically for the purpose of importing tour data from a JSON file into the database.

💡Mongoose

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. It includes built-in methods for creating, querying, updating, and deleting data in MongoDB. In the video, Mongoose is used to connect to the MongoDB database and to create or delete documents within the 'tours' collection.

💡Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Although not the main focus of the script in the video, the script is part of a larger Express application, and the process of importing data is independent of the Express application's main functionality.

💡Environment Variables

Environment variables are a set of dynamic values, set outside the application, that can affect the way running processes will behave on a computer. In the video, the script requires access to environment variables to connect to the database, which is a common practice for managing sensitive information like database credentials.

💡File System Module

The file system module in Node.js provides an API for interacting with the file system. In the script, the file system module is used to read the JSON file containing the tour data that needs to be imported into the MongoDB database.

💡Asynchronous Function

An asynchronous function is a function that can operate independently of the flow of the application, allowing other code to run while waiting for the function to complete. In the video, the script uses asynchronous functions to handle database operations, such as creating documents or deleting data, without blocking the execution of the script.

💡Try-Catch Block

A try-catch block is used in JavaScript to handle errors by allowing developers to write code that attempts to execute a block of code (the 'try' block) and, if an error occurs, handle it in the 'catch' block. In the script, a try-catch block is used to log errors to the console during the data import process.

💡Command Line

The command line is a text-based interface for interacting with a computer's operating system. In the video, the script is run from the command line, and the script's functionality is controlled by command line arguments, such as specifying the 'import' or 'delete' options.

💡Process.argv

Process.argv is an array in Node.js that contains the command-line arguments passed to the script. In the video, process.argv is used to determine which action the script should perform based on the arguments provided when the script is run from the command line.

Highlights

Building a script to import tour data from a JSON file into MongoDB database.

The script is independent of the express application and will be run separately.

Using mongoose for database connection and environment variables from .env package.

Accessing the file system module to read the JSON file.

Importing the tour model to write tours data into the database.

Reading the JSON file synchronously with fs.readFile.

Creating an async function to import data into the database using tour.create.

Using JSON.parse to convert JSON data into JavaScript objects.

Creating a function to delete all data from the collection using deleteMany.

Mongoose's deleteMany method is similar to MongoDB's native function.

Interacting with the command line to run functions based on user input.

Using process.argv to access command line arguments.

Creating a command line application to import or delete data based on options.

Using process.exit to stop the application after running the desired function.

Handling validation errors due to incomplete tour data.

Ensuring that the script exits properly after importing or deleting data.

Finalizing the script with a successful data import into MongoDB.

Transcripts

play00:01

Let's now take a small break

play00:02

from building our API

play00:04

and build a fun little script

play00:07

that will import the tour data from our JSON file

play00:10

into the MongoDB database.

play00:12

And I wasn't really sure

play00:14

if I should include this video in the course

play00:16

or if I should just come with the script

play00:19

already in the course starter files.

play00:22

But I thought I thought it was a nice little exercise

play00:25

and so I included it anyways.

play00:27

So, anyway, let's now get started.

play00:31

So, basically we're gonna create a script

play00:34

that will simply load the data from the JSON file

play00:37

as I just said into the database.

play00:39

And this script is completely independent

play00:42

of the rest of our express application.

play00:44

And so we'll run this completely separately

play00:46

from the comment line just to import everything once.

play00:50

Okay, so let me actually create the script

play00:53

right here in the data folder.

play00:56

So new file,

play00:58

import,

play01:01

dev data.js.

play01:04

All right.

play01:05

So, what are we gonna need for this?

play01:07

We will need mongoose of course

play01:09

so let's start with that.

play01:11

Or actually, let's just go ahead into the server.js file

play01:15

and copy this stuff

play01:16

because why writing it all over again.

play01:20

So let's copy everything

play01:23

and then delete what we don't need.

play01:26

So we don't need our express application

play01:29

we also need the .env package

play01:31

because we need our environment variables

play01:33

in order to be able to connect to the database again, okay.

play01:38

And we need to connect to the database in this script

play01:41

again because it runs completely independent

play01:44

from the express application.

play01:46

It's only gonna run once in the beginning.

play01:48

Next up, we need access to the file system module

play01:52

because of course we want to read the JSON file.

play01:57

So require fs

play01:59

and finally we also need access to the tour model

play02:03

because the tour model is

play02:05

where we want to write the tours to, right?

play02:10

So, tour equals

play02:12

and now let's find the path there

play02:15

so from the place where we are right now

play02:18

we need to go up one level.

play02:21

And what's going on here with these quotes?

play02:25

All right, so one level up

play02:27

and we're in dev data.

play02:29

So we need another level up

play02:32

so that we're in the main folder.

play02:33

And from there we go in to models

play02:36

and into the tour model.

play02:39

Okay and that should be it for setup.

play02:43

Now let's start by reading the file.

play02:47

So, read JSON file

play02:50

and that should be fairly simple.

play02:54

So the tours are at fs.readfile

play02:59

and we can use the synchronous version of course.

play03:02

And let's simply say tours simple.json, okay.

play03:08

And then,

play03:10

also the encoding.

play03:12

So, file encoding, utf eight.

play03:16

Give it a save.

play03:18

And so now we can write the actual function

play03:21

that is gonna import the data into the database.

play03:25

So import data into database.

play03:30

Okay, just like this.

play03:32

And so let's create this function.

play03:33

Import data, import data,

play03:37

yep.

play03:39

And that's gonna be and async function

play03:43

which does not need any arguments

play03:45

and so let's again use a try catch block here.

play03:53

And here I'm simply gonna log it to the console

play03:57

if there is some error,

play03:58

just to know what's going on in that case.

play04:02

And now here,

play04:03

what we will do is very simple.

play04:05

We are simply gonna await,

play04:08

tour.create.

play04:10

So we already used tour.create

play04:13

and we pass then an object back then right?

play04:16

But the create method can also accept an array of objects.

play04:20

And in that case

play04:22

it will then simply create a new document

play04:24

for each of the objects in the array.

play04:27

So, very simple,

play04:28

all we have to do is to specify our tours data here, right?

play04:34

And actually it's not 100% correct

play04:37

because remember that this is JSON.

play04:40

And so we need to first convert it actually

play04:42

into a JavaScript object using json.parse.

play04:49

Okay and so now we actually have

play04:52

an array of JavaScript objects

play04:54

that we can now pass into the create method, okay.

play04:59

And if that was successful,

play05:00

then the next line is gonna be executed

play05:04

and so here we can say data successfully

play05:10

loaded, all right.

play05:12

And this should already do the job.

play05:15

Now what about the data that is already in the database?

play05:19

We can also create an easy way

play05:21

to basically delete all of that data at the same time.

play05:24

And so let's simply go ahead and do that as well.

play05:28

So, delete all data

play05:31

from collection, let's say.

play05:35

And this weird yellow color that you see here

play05:37

actually comes from an extension that I have installed here.

play05:41

And so to get rid of that,

play05:42

I'm simply gonna write database again, okay.

play05:47

So delete data

play05:50

and again this is gonna be an async function

play05:53

without any arguments.

play05:57

And let me actually copy this code here.

play06:01

So, delete it

play06:05

and now about the deleting itself

play06:07

we can use the delete many function.

play06:11

Okay and actually I showed you this one

play06:14

back in the intro to MongoDB, right?

play06:18

Where we could use delete many

play06:19

and then simply pass in nothing in there

play06:22

and that would then delete

play06:23

all of the documents in a certain collection, right?

play06:26

And so mongoose basically implemented

play06:29

the same function here on the model, okay.

play06:33

So in this case,

play06:34

the tour model has access to this delete many method

play06:37

which will then do exactly the same

play06:39

as delete many does in native MongoDB, right?

play06:43

So, remember that mongoose is just a,

play06:46

like a layer of abstraction on top of MongoDB.

play06:49

Which is why it doesn't use the exact same functions

play06:52

but it still gives us access to some similar ones

play06:56

or to ones that actually have the same name.

play06:58

So delete many actually has the same name

play07:00

as the native MongoDB function, all right?

play07:03

So again, what this is gonna do is to simply go ahead

play07:06

and delete all the documents in the tours collection.

play07:10

So, we have our two functions here

play07:12

but if we now actually run this file

play07:15

then nothing will happen.

play07:16

And that's because

play07:17

we're not calling any of these functions anywhere, right?

play07:21

Now we could go ahead

play07:22

and simply write something like import data here

play07:26

and then simply call the function here

play07:29

but I wanted to make this a little bit more fun.

play07:32

So let's now actually learn a tiny little bit

play07:34

about interacting with the command line, okay.

play07:38

And so I'm actually gonna go ahead

play07:39

and run this file without calling any of these functions.

play07:43

But instead I'm gonna log to the console

play07:47

process.argv,

play07:51

okay.

play07:52

Just so we can see what process.argv actually is

play07:55

so that we can then use it.

play07:57

All right.

play07:58

Let me open up here another terminal

play08:01

and then I will use node,

play08:03

go into dev data

play08:05

then into data

play08:06

and then in there import dev data.

play08:08

And we get some errors here.

play08:11

Let's see where.

play08:12

Ah, yeah so it's because of this,

play08:15

of this file name.

play08:17

So I guess we should specify the path to there basically.

play08:22

So let's run this one again

play08:24

and again we have this error.

play08:26

And yeah, of course I get this error.

play08:30

That's a stupid one.

play08:31

Remember how I told you

play08:32

that this dot here is always relative from the folder

play08:36

where the node application was actually started.

play08:39

And so that's the home folder.

play08:40

And so we're basically looking for this file here

play08:42

in the home folder, okay.

play08:45

So what I should use instead is the dir name,

play08:49

variable that is available to us everywhere.

play08:52

So that goes like this.

play08:58

All right.

play09:00

Give it another save

play09:01

and clear up the console and run it again.

play09:05

And so now it works.

play09:07

And so here

play09:08

is the result of this console.log that we have down here,

play09:11

So process.argv

play09:14

and basically that is an array

play09:16

of these two arguments of running this node process.

play09:20

So, this here is basically

play09:22

where the node command is located.

play09:24

So this equivalent to this node

play09:26

and then the second one,

play09:28

so this path to this file is actually this here, okay.

play09:33

So let's quit this here

play09:35

and let's add kind of an option here.

play09:39

So I'm gonna write,

play09:40

dash, dash import

play09:41

and so I'm sure you have seen something like this

play09:43

many times before.

play09:44

For example, when we save a package as a dev dependency

play09:47

we do it like this.

play09:50

Save dev, and so we use the same

play09:53

kind of format for specifying options.

play09:55

Okay so, dash dash

play09:57

and then whatever string we put here.

play09:59

And so I choose to basically specify

play10:03

the import option like this.

play10:05

And so you see that now the third argument

play10:07

is dash dash import, all right?

play10:10

And so that means that we can now go ahead

play10:12

and basically use this data here

play10:15

in order to write

play10:16

a very simple command line application basically

play10:19

which will import the data when we specify this option

play10:22

and will delete the data

play10:24

when we specify the delete option, all right?

play10:28

So, let's actually do that.

play10:32

So, if

play10:34

process.argv

play10:37

and it's an array

play10:38

and we want the third.

play10:40

So zero, one, two.

play10:44

So if that element is equal to import

play10:50

well, then we want to run import data.

play10:55

Right?

play10:58

If...

play11:00

Process.argv two

play11:04

is equal,

play11:09

to delete then we want to run

play11:15

delete data.

play11:16

And that's it.

play11:19

So, that should actually give us

play11:21

the result that we're looking for.

play11:23

Let's finish this here.

play11:25

And so now let's run the command here

play11:27

with delete in order to delete all the data

play11:30

that we have in the database.

play11:32

So let's try that out.

play11:35

It's doing something

play11:36

and data successfully deleted.

play11:39

So let's take a look at that now.

play11:42

And if we run now this get all tours route

play11:46

then indeed we have zero results.

play11:49

So, all our tours are now gone.

play11:52

So it worked.

play11:54

Now this process here is basically still running.

play11:57

And so let's quickly fix that,

play11:59

which is kind of easy.

play12:01

So, that's a new one we haven't used yet.

play12:03

Which is process.exit,

play12:07

All right?

play12:08

Now this process.exit is kind of an aggressive way

play12:12

of stopping an application

play12:14

but in this case it's no problem

play12:16

because it's really just a very small script

play12:19

that we're running here and not a real application, right?

play12:23

Let's just copy the same thing here

play12:24

into our import data function.

play12:27

And so now I'm gonna quit it.

play12:30

And just to show that it works

play12:32

I'm gonna run it again

play12:34

so data successfully deleted

play12:36

and then it exited the process.

play12:39

All right.

play12:40

And so now it's time to actually run the function

play12:43

that we were interested in in the first place.

play12:47

So with the import flag, basically.

play12:50

So the import option.

play12:52

So let's run that

play12:53

and let's see if it actually works.

play12:56

And it didn't.

play12:57

So why is that?

play13:00

So it tells us here a tour must have a group size.

play13:05

So where's that coming from?

play13:07

And we see a lot of validation errors here.

play13:10

So something must have gone wrong here.

play13:14

So yeah, we have the cover image,

play13:15

we have the tour description.

play13:20

We have the price.

play13:22

Well, that's weird.

play13:23

Max group size,

play13:26

let me actually check if anything happened here.

play13:30

Actually we have nine tours here

play13:32

and I think nine is actually all we have.

play13:35

And so to me it kind of looks like it actually did work.

play13:39

But let's actually take a quick look at our data here.

play13:43

So, just to figure out why this actually happens.

play13:48

So tour simple here

play13:52

and so we can already see,

play13:53

actually the problem that is happening.

play13:57

So we have all these tours

play13:58

so the original ones.

play14:00

But then from the last section,

play14:02

we have these three here

play14:04

that we kind of added using our file based API.

play14:08

So, remember that?

play14:09

So back then we only specified the name, duration

play14:12

and difficulty and nothing else.

play14:14

And so right now

play14:16

our script is trying to import these three tours.

play14:19

But of course, we're not interested in them at all

play14:23

and so let's go ahead and save this here, okay.

play14:28

Then quit this process

play14:29

and so actually this process.exit

play14:32

can be outside of the try catch block

play14:35

and be simply here by the end of the function.

play14:36

So that no matter if there's an error or not

play14:37

it will always just exit the process.

play14:43

All right.

play14:45

So let's delete everything.

play14:49

All right, clear the console again.

play14:51

Now import,

play14:54

and yeah.

play14:55

So data successfully loaded.

play14:59

As indeed here we are again.

play15:02

So now it's working 100%,

play15:04

we have our data that we can start working with now

play15:08

and so, yeah.

play15:09

Our work with this one here is done.

play15:12

So, a nice little function,

play15:14

or a nice little script actually.

play15:16

I hope that everything made sense to you

play15:20

and yeah that it was kind of a fun exercise for you as well.

play15:25

Anyway, see you in the next video

play15:26

where we are finally starting to then use all this data

play15:31

and to improve our API

play15:32

by implementing a couple of nice features.

Rate This

5.0 / 5 (0 votes)

関連タグ
MongoDBJSON ImportAPI ScriptingData IntegrationNode.jsMongoose ORMScript TutorialDatabase ManagementExpress AppDevOps
英語で要約が必要ですか?