Загрузка...

How to Bulk Import Data into MongoDB from Node JS | Building a Custom Mongoose Script | Part #107

🚀 Introduction:
Stop manually adding documents one by one! In this lecture, we take a short break from our main API development to build a powerful Utility Script. This script will read a JSON file containing 30+ hotel documents and "seed" our MongoDB database automatically. We’ll learn how to handle file systems in Node.js, use command-line arguments, and manage asynchronous database operations outside of an Express environment.

🤔 What you will learn in this video?
✔️ The fs Module: Reading JSON files synchronously using readFileSync.
✔️ process.argv: How to pass custom flags like --import or --delete to your Node scripts.
✔️ Mongoose create() for Arrays: Did you know .create() can insert an entire array of objects at once?
✔️ Database Seeding Logic: Why we usually delete existing data before importing new "clean" test data.
✔️ Process Management: Using process.exit() to gracefully close database connections once the script finishes.

💪 The Power of process.argv
When you run node script.js --import, Node.js creates an array called process.argv:
1️⃣ Index 0: Path to the Node executable.
2️⃣ Index 1: Path to the script being run.
3️⃣ Index 2: Your custom argument (--import).
By checking process.argv[2], we can make one script perform multiple tasks!

⚠️ Instructor's "Async" Warning
Remember why the script failed the first time? Database calls are asynchronous. If you call process.exit() at the bottom of your file, Node will kill the script before the database has finished importing the data.
👉 The Solution: Always place process.exit() inside the .then() block or after your await calls inside the try/catch block to ensure the work is done before the lights go out!

⏱️ Timelines:
0:00 - Introduction to Data Seeding
1:45 - Setting up the import-script.js file
3:30 - Connecting Mongoose independently from Express
5:10 - Reading and Parsing the hotels.json file
7:20 - Writing the deleteDocuments() function
10:15 - Writing the importDocuments() function
12:30 - Mastering process.argv: Handling CLI options
15:00 - Fixing the process.exit() async bug
18:45 - Live Demo: Deleting and Importing 33 Hotels in 2 seconds
20:10 - Summary and Use Cases

👍 Build tools that save you time! Like and Subscribe for more Node.js automation tips! #NodeJS #MongoDB #Mongoose #DatabaseSeeding #Automation #WebDev2026 #ProcademyClasses

Видео How to Bulk Import Data into MongoDB from Node JS | Building a Custom Mongoose Script | Part #107 канала procademy
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять