Home > Software engineering >  MongoDB - find returns empty where findOne does not
MongoDB - find returns empty where findOne does not

Time:12-29

I'm tearing my hair out, trying to write a simple query in MongoDB Application Services, which I believe uses Mongoose in Node.js.

I have a simple collection with Users, and I'm trying to find a set of users.

In testing, this prints a single user, as expected:

exports = async function(){
  db = context.services.get("mongodb-atlas").db("2021_10_DB");
  const user_col = db.collection("Users");
  alarmingSubjs = await user_col.findOne();
  console.log(JSON.stringify(alarmingSubjs));
  return "Done";
}
====== log ======
> ran at 1672322424787
> took 691.479418ms
> logs: 
{"_id":"61807c0fd8c5df7ff5d09571",...}     <----- prints entire document for a single user
> result: 
"Done"
> result (JavaScript): 
EJSON.parse('"Done"')

but, switching findOne to find prints no users, which is not expected. (ref db.collection.find() and querying documents)

exports = async function(){
  db = context.services.get("mongodb-atlas").db("2021_10_DB");
  const user_col = db.collection("Users");
  alarmingSubjs = await user_col.find();
  console.log(JSON.stringify(alarmingSubjs));
  return "Done";
}
====== log ======
> ran at 1672322583386
> took 443.279884ms
> logs: 
{}                         <------ no documents
> result: 
"Done"
> result (JavaScript): 
EJSON.parse('"Done"')

I tried:

  • removing async and await, this makes both find and findOne return an empty object
  • embedding a function in find, which is not discussed in the documentation that I found, but is discussed in a few stack overflow questions (example), doing this:
// tried this
db.collection("Users").find({}, (err, user) => {
  console.log(JSON.stringify(user));
});

//and this
db.collection("Users").find({}, (err, user) => {
  console.log(user);
});

both result in

> ran at 1672323629660
> took 273.490161ms
> result: 
"Done"
> result (JavaScript): 
EJSON.parse('"Done"')
  • I tried using runCommand but I get TypeError: 'runCommand' is not a function

CodePudding user response:

This does not look like Mongoose, it looks like the regular Node.js Mongo driver.

Which would return a cursor object from find(), as shown in the documentation here.

Please try

alarmingSubjs = await user_col.find().toArray();

Which would enumerate the cursor and return an array.

  • Related