Connecting to MongoDB
Use Mongoose to connect your Node.js application to MongoDB and define data models.
const mongoose = require('mongoose');
async function connectToDatabase() {
try {
// Connect to MongoDB using the provided connection string
await mongoose.connect('mongodb://127.0.0.1:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true
});
console.log("Database Connected");
} catch (error) {
console.error("Error connecting to database:", error);
}
}
connectToDatabase();
// Define the user schema and model
// after establishing the connection
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
email: String,
age: Number
});
// Create a User model based on the userSchema
const User = mongoose.model('User', userSchema);
// Export the User model to use it elsewhere if needed
module.exports = User;
Output:
Node.js Basics: Back-End Development in MERN Stack
Node.js is an open-source and cross-platform JavaScript runtime environment. It’s a powerful tool suitable for a wide range of projects. Node.js stands out as a game-changer. Imagine using the power of JavaScript not only in your browser but also on the server side.
Table of Content
- What is MERN stack?
- What is Node?
- Why Node?
- Key features of Node
- Node Advantages
- How NodeJS works?
- Creating a Simple Node Application
- Conclusion