Integrating MongoDB with Mongoose
Lesson 2
Welcome back to the "Unlock The Blockchain" course, where Lesson 2 delves into integrating MongoDB with Mongoose for our Crypto Portfolio Tracker app. This chapter aims to equip you with the skills to use MongoDB to manage essential data like user authentication details and cryptocurrency wallet addresses, thereby boosting your app's functionality and security.
Objective:
We aim to utilize MongoDB to store and manage critical data securely and efficiently, making our app more robust and user-friendly.
Why Mongoose and dotenv?
Mongoose simplifies data modeling and database operations in Node.js, allowing for more readable and maintainable code. Mongoose Documentation
dotenv safely stores sensitive configurations, such as database connections, outside your codebase to prevent security breaches.
Getting Started with Mongoose and dotenv:
Install Dependencies:
npm install mongoose dotenv npm install --save-dev @types/mongoose @types/dotenv
Configure dotenv:
Create a .env file at your project root.
Add your MongoDB connection URI:
MONGODB_URI=mongodb+srv://your_mongodb_connection_string_here
Connect to MongoDB with Mongoose:
In your src/server.ts add:
import mongoose from "mongoose";
import dotenv from "dotenv";
dotenv.config();
const app: Application = express();
const port = 3000;
mongoose
.connect(process.env.MONGODB_URI as string)
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.log("MongoDB connection error", err));
Define a User Model:
In models/User.ts:
import mongoose, { Schema, Document } from "mongoose";
interface IUser extends Document {
username: string;
password: string;
bitcoinAddress?: string;
ethereumAddress?: string;
}
const UserSchema: Schema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
bitcoinAddress: { type: String },
ethereumAddress: { type: String },
});
export default mongoose.model<IUser>("User", UserSchema);
MongoDB vs. Mongoose for Queries:
MongoDB Query:
db.users.find({ username: "cryptoFan" })
Mongoose Query:
User.findOne({ username: "cryptoFan" }).then(user => console.log(user));
Mongoose queries are more intuitive and integrate seamlessly into your JavaScript code, providing richer data manipulation and retrieval features.
Conclusion:
By integrating MongoDB with Mongoose and dotenv for configuration management, you've laid a strong foundation for your Crypto Portfolio Tracker's backend. This combination ensures secure and efficient data handling. It allows you to add complex functionalities like user authentication and wallet management.
Looking Ahead:
Our journey continues further. Next, we'll tackle user authentication with Passport.js, further enhancing your blockchain development skills. Stay tuned, and let's continue to build and learn together in this exciting blockchain adventure! 🚀
Last updated