Created
June 18, 2025 10:19
-
-
Save Gulshanidrees/afc71eaae2ae8a3e7a21392624d379e0 to your computer and use it in GitHub Desktop.
send me the code of mongoose in expressjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const mongoose = require('mongoose'); | |
const app = express(); | |
app.use(express.json()); | |
mongoose.connect('mongodb://localhost:27017/mydatabase', { | |
useNewUrlParser: true, | |
useUnifiedTopology: true | |
}); | |
const db = mongoose.connection; | |
db.on('error', console.error.bind(console, 'connection error:')); | |
db.once('open', () => { | |
console.log('Connected to MongoDB'); | |
}); | |
const mySchema = new mongoose.Schema({ | |
name: String, | |
age: Number | |
}); | |
const MyModel = mongoose.model('MyModel', mySchema); | |
app.post('/mymodel', async (req, res) => { | |
try { | |
const newModel = new MyModel(req.body); | |
const savedModel = await newModel.save(); | |
res.status(201).json(savedModel); | |
} catch (error) { | |
res.status(500).json({ error: error.message }); | |
} | |
}); | |
app.get('/mymodel', async (req, res) => { | |
try { | |
const models = await MyModel.find({}); | |
res.json(models); | |
} catch (error) { | |
res.status(500).json({ error: error.message }); | |
} | |
}); | |
app.listen(3000, () => { | |
console.log('Server listening on port 3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment