Node.js - MongoDB 創建數據庫

Hello there, aspiring programmers! Today, we're going to embark on an exciting journey into the world of Node.js and MongoDB. As your friendly neighborhood computer science teacher, I'm here to guide you through the process of creating a database using these powerful tools. Don't worry if you're new to programming – we'll start from the basics and work our way up. So, grab a cup of coffee (or your favorite beverage), and let's dive in!

Node.js - MongoDB Create Database

What is MongoDB?

Before we start creating databases, let's take a moment to understand what MongoDB is. Imagine you have a giant digital filing cabinet where you can store all sorts of information. That's essentially what MongoDB is – a database that stores data in a flexible, JSON-like format called BSON (Binary JSON). It's like having a super-organized assistant who can quickly find and retrieve any piece of information you need.

Connection Strings: Your Gateway to MongoDB

Now that we know what MongoDB is, let's talk about how we connect to it. Think of a connection string as a secret handshake between your Node.js application and MongoDB. It contains all the information needed to establish a connection, like the address of the MongoDB server, the port number, and any authentication details.

Here's what a typical MongoDB connection string looks like:

mongodb://username:password@hostname:port/database

Let's break this down:

  • mongodb://: This is the protocol, telling your application that it's connecting to a MongoDB database.
  • username:password: Your login credentials (if required).
  • hostname: The address of the MongoDB server (e.g., localhost for your own machine).
  • port: The port number MongoDB is listening on (default is 27017).
  • database: The name of the database you want to connect to.

Example: List of Databases

Now, let's get our hands dirty with some code! We'll start by connecting to MongoDB and listing all the databases. This is a great way to check if our connection is working and see what databases already exist.

const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });

// Connect to the server
client.connect(function(err) {
if (err) {
console.error('Failed to connect to MongoDB:', err);
return;
}

console.log("Connected successfully to server");

// Get the admin database
const adminDb = client.db(dbName).admin();

// List all the available databases
adminDb.listDatabases(function(err, dbs) {
if (err) {
console.error('Failed to list databases:', err);
return;
}

console.log("Databases:");
dbs.databases.forEach(function(db) {
console.log(" - " + db.name);
});

client.close();
});
});

Let's break this code down:

  1. We start by requiring the MongoDB driver for Node.js.
  2. We set up our connection URL and database name.
  3. We create a new MongoClient with some options for better performance.
  4. We use the connect method to establish a connection to MongoDB.
  5. If the connection is successful, we get the admin database.
  6. We use the listDatabases method to get a list of all databases.
  7. We print out the names of all the databases.
  8. Finally, we close the connection.

When you run this code, you'll see a list of all the databases in your MongoDB instance. It's like asking your digital filing cabinet, "Hey, what folders do you have?"

Create a New Database

Now for the exciting part – creating our very own database! In MongoDB, databases and collections are created automatically when you first store data in them. It's like magic – you don't need to explicitly create them beforehand.

Let's create a new database called "myNewDB" and add a collection called "students":

const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myNewDB';

// Create a new MongoClient
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });

// Connect to the server
client.connect(function(err) {
if (err) {
console.error('Failed to connect to MongoDB:', err);
return;
}

console.log("Connected successfully to server");

// Get the database
const db = client.db(dbName);

// Create a new collection
db.createCollection("students", function(err, res) {
if (err) {
console.error('Failed to create collection:', err);
return;
}

console.log("Collection created!");

// Insert a document
db.collection('students').insertOne({
name: "John Doe",
age: 20,
grade: "A"
}, function(err, res) {
if (err) {
console.error('Failed to insert document:', err);
return;
}

console.log("Document inserted");

// Close the connection
client.close();
});
});
});

Let's break down what's happening here:

  1. We connect to MongoDB just like before.
  2. We use client.db(dbName) to get our new database. If it doesn't exist, MongoDB will create it for us.
  3. We create a new collection called "students" using db.createCollection().
  4. We insert a document into our new collection using insertOne().
  5. Finally, we close the connection.

When you run this code, MongoDB will create the "myNewDB" database and the "students" collection, and insert a document with John Doe's information. It's like creating a new filing cabinet, adding a folder called "students", and putting John's file in it.

Conclusion

Congratulations! You've just learned how to connect to MongoDB, list existing databases, and create a new database with a collection. You're well on your way to becoming a database wizard!

Remember, practice makes perfect. Try creating different databases, collections, and inserting various types of documents. Experiment with querying the data you've inserted. The more you play around with MongoDB, the more comfortable you'll become.

Here's a table summarizing the main methods we've used:

Method Description
MongoClient.connect() Establishes a connection to MongoDB
client.db() Gets a reference to a database
adminDb.listDatabases() Lists all available databases
db.createCollection() Creates a new collection
collection.insertOne() Inserts a document into a collection

Happy coding, and may your databases always be organized and your queries lightning-fast!

Credits: Image by storyset