Mongo DB를 연동하기 위해 mongodb 라는 드라이버 모듈을 사용해본다. mongodb 모듈을 사용하는 이유는 Mongo DB의 명령어들을 자연스럽게 사용할 수 있기 때문이다.
https://javafa.gitbooks.io/nodejs_server_basic/content/chapter13.html
실습 : MongoDB와 연동 (db명 : test, collection명 : customer, field 명 : name, age, gender )----------------------------
먼저 npm install mongodb 한 후 코드를 작성하자.
import { MongoClient } from 'mongodb';
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("test");
const collection = db.collection("customer");
// Document count
const count = await collection.countDocuments();
console.log("자료 건수 :", count);
// First document
const firstDocument = await collection.findOne();
console.log("첫번째 자료 :", firstDocument);
// All documents
console.log("전체 자료 --------");
const allDocuments = await collection.find().toArray();
allDocuments.forEach(doc => {
console.log(doc);
});
// Specific fields
console.log();
allDocuments.forEach(doc => {
console.log(`이름: ${doc.name}, 나이: ${doc.age}, 성별: ${doc.gender}`);
});
// Using forEach with a callback function
console.log("---Consumer 사용-----");
await collection.find().forEach(doc => {
const name = doc.name;
const age = doc.age;
console.log(`${name}님의 나이는 ${age}`);
});
} catch (err) {
console.error("err :", err.message);
} finally {
await client.close();
}
}
main().catch(console.error);