-
Notifications
You must be signed in to change notification settings - Fork 80
/
testmongo.js
54 lines (42 loc) · 1.6 KB
/
testmongo.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
const { MongoClient } = require("mongodb");
// The uri string must be the connection string for the database (obtained on Atlas).
const uri = "mongodb+srv://<user>:<password>@ckmdb.5oxvqja.mongodb.net/?retryWrites=true&w=majority";
// --- This is the standard stuff to get it to work on the browser
const express = require('express');
const app = express();
const port = 3000;
app.listen(port);
console.log('Server started at http://localhost:' + port);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// routes will go here
// Default route:
app.get('/', function(req, res) {
res.send('Starting... ');
});
app.get('/say/:name', function(req, res) {
res.send('Hello ' + req.params.name + '!');
});
// Route to access database:
app.get('/api/mongo/:item', function(req, res) {
const client = new MongoClient(uri);
const searchKey = "{ partID: '" + req.params.item + "' }";
console.log("Looking for: " + searchKey);
async function run() {
try {
const database = client.db('ckmdb');
const parts = database.collection('cmps415');
// Hardwired Query for a part that has partID '12345'
// const query = { partID: '12345' };
// But we will use the parameter provided with the route
const query = { partID: req.params.item };
const part = await parts.findOne(query);
console.log(part);
res.send('Found this: ' + JSON.stringify(part)); //Use stringify to print a json
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
});