MongoDB + Node.js

Einrichten

  • MongoDB Modul für Node.js installieren (in Projektordner)
    • npm install mongodb

MongoDB in Node.js verwenden

MongoDB Modul in Node.js Code verwenden

Codeconst mongodb = require('mongodb');

Mit Datenbank verbinden

Codeconst url = 'mongodb://127.0.0.1:27017'; // für lokale MongoDB
const mongoClient = new mongodb.MongoClient(url, options);
await mongoClient.connect();

MongoDB Verbindungs-URL Aufbau

Collection auswählen

Codeconst collection = mongoClient.db('db_name').collection('collection_name');
await collection.insert({...});
console.log(await collection.find({...}).toArray());
  • Befehle von Kommandozeile genauso in JavaScript verwendbar (MongoDB muss gestartet sein)
  • Ausnahme: find gibt ein Cursor Objekt zurück, welches mit toArray() in ein Array gewandelt werden kann

Node.js Beispiel

Codeconst mongodb = require('mongodb');

const mongoUrl = 'mongodb://127.0.0.1:27017'; // für lokale MongoDB
const mongoClient = new mongodb.MongoClient(mongoUrl);

async function main() {
  await mongoClient.connect();
  const db = mongoClient.db("university");
  const studentCollection = db.collection("student");

  const newStudent = {
    studentNr: 333333,
    firstName: "Max",
    lastName: "Mustermann",
    semester: 1,
    faculty: "DM",
    course: "OMB",
  };
  await studentCollection.insertOne(newStudent);
  const students = await studentCollection.find({ studentNr: 333333 }).toArray();
  console.log(students);
  await mongoClient.close();
}

main();