Connecting with MongoDB & Mongoose
Prerequisites
Step 1: Setting Up Your Node.js Project
mkdir mongoose-nodejs-tutorial cd mongoose-nodejs-tutorialnpm init -ynpm install express mongoose
mkdir mongoose-nodejs-tutorial
cd mongoose-nodejs-tutorialnpm init -ynpm install express mongoosemongodconst express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
// Replace with your MongoDB URI
const mongoURI = 'mongodb://localhost:27017/mongoose_tutorial';
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch(err => {
console.error('Error connecting to MongoDB', err);
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});const mongoURI = 'your_atlas_connection_string';const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
age: {
type: Number,
required: true,
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;const User = require('./models/User');
app.use(express.json()); // For parsing application/json
app.post('/users', async (req, res) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
} catch (error) {
res.status(400).send(error);
}
});app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.status(200).send(users);
} catch (error) {
res.status(500).send(error);
}
});app.patch('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
if (!user) {
return res.status(404).send();
}
res.send(user);
} catch (error) {
res.status(400).send(error);
}
});app.delete('/users/:id', async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) {
return res.status(404).send();
}
res.send(user);
} catch (error) {
res.status(500).send(error);
}
});node app.js