-
Notifications
You must be signed in to change notification settings - Fork 0
/
server1.js
85 lines (63 loc) · 2.66 KB
/
server1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const express = require('express')
// const bodyParser = require('body-parser')
// Create an Express.js instance:
const app = express()
// config Express.js
app.use(express.json())
app.set('port', 3000)
app.use ((req,res,next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
})
const MongoClient = require('mongodb').MongoClient;
var db;
MongoClient.connect("mongodb+srv://mesum:saif@cluster0.qyb90.mongodb.net/test", (err, client) =>{
db = client.db('webstore')
})
app.get('/', (req, res, next) =>{
res.send('Select a collection, e.g., /collection/products')
})
// get the collection name
app.param('collectionName', (req, res, next, collectionName) => {
req.collection = db.collection(collectionName)
console.log('collection name:', req.collection.collectionName)
return next()
})
app.post('/collection/collectionName', (req, res, next)=>{
req.collection.insert(req.body, (e, results) =>{
if(e) return next(e)
res.send(results.ops)
})
})
const ObjectID = require('mongodb').ObjectID; app.get('/collection/:collectionName/:id', (req, res, next) => {
req.collection.findOne({ _id: new ObjectID(req.params.id) }, (e, result) => {
if (e) return next(e)
res.send(result)
}) })
app.get('/collection/:collectionName', (req, res, next) => {
req.collection.find({}).toArray((e, results) => {
if (e) return next(e)
res.send(results)
})
})
app.put('/collection/:collectionName/:id', (req, res, next) => {
req.collection.update(
{_id: new ObjectID(req.params.id)},
{$set: req.body},
{safe: true, multi: false},
(e, result) => {
if (e) return next(e)
res.send(
result.modifiedCount === 1 ? { msg: "success" } : { msg: "error" });
})
})
app.delete('/collection/:collectionName/:id', (req, res, next) => {
req.collection.deleteOne(
{_id: ObjectID(req.params.id)}, (e, result) => {
if (e) return next(e)
res.send((result.modifiedCount === 1) ? {msg: 'success'} : {msg: 'error'}) })
})
const port = process.env.port || 3000
app.listen(port, () =>{
console.log(port)
})