카테고리 없음

[06.03] 몽고DB - Find쿼리 결과를 변수에 저장

ljw4104 2021. 6. 3. 16:13
const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'mongodb+srv://<ID>:<Password>@djs.brrz0.mongodb.net/Dialog?retryWrites=true&w=majority';

// Database Name
const dbName = DBNAME;
const client = new MongoClient(url);
// Use connect method to connect to the server
let sampleData;
client.connect(function (err) {
  console.log('Connected successfully to server');

  const db = client.db(dbName);
  findDocuments(db, COLLECTIONNAME, function (docs) {
    sampleData = docs;
    console.log(sampleData);
  });

  //client.close();
});

const findDocuments = function (db, chapterName, callback) {
  // Get the documents collection
  const collection = db.collection(chapterName);
  // Find some documents
  collection.find({}, { fields: { _id: 0 } }).toArray(function (err, docs) {
    callback(docs);
  });
};

console.log(sampleData);
client.close();

전에 Find까지 성공을 시켰다.

이번에는 몽고db의 고유 인덱스인 _id를 쿼리로 제거한 값 출력과 변수를 통해 Find쿼리 값을 외부에서 불러오게 하였다.

왜 안됐었는지 궁금했었는데 콜백으로 결과를 받은 뒤에 client.close를 밑으로 내리니 잘된다.