0% found this document useful (0 votes)
14 views

CRUD Operations in Node Js With MongoDB

crud mongo

Uploaded by

goktasorhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

CRUD Operations in Node Js With MongoDB

crud mongo

Uploaded by

goktasorhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

2. CRUD Operations in Node.

js with
MongoDB
Node.js is commonly used with MongoDB to create dynamic web applications. Here's how to
create basic CRUD operations using Express and MongoDB:

```javascript
const express = require('express');
const mongoose = require('mongoose');
const app = express();

mongoose.connect('mongodb://localhost/my_database', { useNewUrlParser: true });

const UserSchema = new mongoose.Schema({


name: String,
email: String
});

const User = mongoose.model('User', UserSchema);

app.use(express.json());

// Create
app.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.send(user);
});

// Read
app.get('/users', async (req, res) => {
const users = await User.find();
res.send(users);
});

// Update
app.put('/users/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(user);
});
// Delete
app.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.send({ message: 'User deleted' });
});

app.listen(3000, () => console.log('Server running on port 3000'));


```

You might also like