Beispielanwendung zum Hinzufügen und Auslesen von Studenten Informationen (async/await beachten)
Codeconst http = require('http');
const mongodb = require('mongodb');
const hostname = '127.0.0.1'; // localhost
const port = 3000;
const url = 'mongodb://127.0.0.1:27017'; // für lokale MongoDB
const mongoClient = new mongodb.MongoClient(url);
async function startServer() {
// connect to database
await mongoClient.connect();
// listen for requests
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
}
const server = http.createServer(async (request, response) => {
response.statusCode = 200;
response.setHeader('Access-Control-Allow-Origin', '*'); // bei CORS Fehler
let url = new URL(request.url || '', `http://${request.headers.host}`);
switch (url.pathname) {
case '/student': {
const studentCollection = mongoClient.db('university').collection('student');
switch (request.method) {
case 'GET':
let result;
if(url.searchParams.get('studentNr')){
result = await studentCollection.find({
studentNr: Number(url.searchParams.get('studentNr')), // von String zu Zahl konvertieren
}).toArray();
}
else {
result = await studentCollection.find({}).toArray();
}
response.setHeader('Content-Type', 'application/json');
response.write(JSON.stringify(result));
break;
case 'POST':
let jsonString = '';
request.on('data', data => {
jsonString += data;
});
request.on('end', async () => {
studentCollection.insertOne(JSON.parse(jsonString));
});
break;
}
break;
}
case '/clearAll':
await mongoClient.db('university').collection('student').drop();
break;
default:
response.statusCode = 404;
}
response.end();
}
);
startServer();
Über URLs testen:
JavaScriptasync function addStudent(url, jsonString) {
const response = await fetch(url, {
method: 'post',
body: jsonString,
});
}
async function getStudent(studentNr) {
const response = await fetch(
`http://127.0.0.1:3000/student?studentNr=${studentNr}`
);
const text = await response.text();
console.log(JSON.parse(text));
}
async function getAllStudents() {
const response = await fetch('http://127.0.0.1:3000/student');
const text = await response.text();
console.log(JSON.parse(text));
}
async function test() {
await addStudent(
'http://127.0.0.1:3000/student',
JSON.stringify({
studentNr: 111111,
firstName: 'Adam',
lastName: 'Anfang',
semester: 1,
faculty: 'DM',
course: 'MKB',
})
);
await getStudent(111111);
await getAllStudents();
}
test();
Meist wird keine eigene ID vergeben (wie bei studentenNr), sondern die automatisch von MongoDB erzeugte _id zum Zugriff (read, update, delete) verwendet
_id
hinzugefügtnew mongodb.ObjectId(id)
Beispiel Verwendung im Code:
Coderesult = await studentCollection.find({
_id: new mongodb.ObjectId(url.searchParams.get('id')), // von String/Zahl zu ObjectID konvertieren
});