Skip to content

Instantly share code, notes, and snippets.

@shalaby
Last active February 16, 2021 09:44
Show Gist options
  • Save shalaby/67d22a1b2dab4d631173d6b59e1c0351 to your computer and use it in GitHub Desktop.
Save shalaby/67d22a1b2dab4d631173d6b59e1c0351 to your computer and use it in GitHub Desktop.
Simple news app using Mongo
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
// Mongoose
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/blog', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
// Listen on connection error
db.on('error', function (err) {
console.log(err)
})
// Listen on connection success
db.on('open', function () {
console.log('Connection Established ...')
app.listen(3000, function () {
console.log('Server is running ...')
})
})
// Create Schema
const akhbarSchema = new mongoose.Schema({
title: String,
content: String
})
// Create Model
const KhabarModel = mongoose.model('Khabar', akhbarSchema)
// Mongoose
app.get('/', function (req, res) {
KhabarModel.find(function (err, result) {
res.send(result)
})
})
app.get('/save', function (req, res) {
const enwanAlkhabar = req.query.formTitle
const nasAlkhabar = req.query.formContent
const khabarGadid = new KhabarModel({
title: enwanAlkhabar,
content: nasAlkhabar
})
khabarGadid.save(function (err, result) {
res.send('Saved successfully.')
})
})
app.get('/:x', function (req, res) {
const khabarId = req.params.x
KhabarModel.findById(khabarId, function (err, result) {
res.send(result)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment