简体   繁体   中英

`find()` Not Working Like `findOne()` After Connecting to MongoDB Via Node

I am familiar with how to get documents from the Mongo shell, but am having difficulty getting documents using find() when connecting via Node.

What I'm getting right now looks like a lot of cursor info, but not the actual documents.

What do I need to change with the following code so that I get the actual documents logged to the console for 'results'?

const config = require('./../../../configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');

const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);

module.exports = async function getSchedules() {
  let results;
  return new Promise((resolve, reject) => {
    client.connect(async function (err) {
      if (err) return reject(err);
      try {
        const db = await client.db(dbName);
        results = await db.collection('schedules').find();
      } catch (error) {
        return reject(error);
      }
      return resolve(results);
    });
  });
};

... And here's where I actually try and get the documents:

async function getSchedulesFromDB() {
  await getSchedules().then((schedules => {
    console.log('schedules: ', schedules); // expect result here
    return schedules;
  }));
}

When I used this same kind of code structure on a findOne() , it worked. But here when using a find() it is not. What am I missing? Does find() work fundamentally differently than findOne() ?

Yes. find() returns a cursor over which you must iterate. findOne() returns a single doc, not a cursor. If you want an array of results, you must "build it yourself" by iterating the cursor, something like:

results = [];
db.collection('schedules').find().forEach(function(d) { results.push(d); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM