简体   繁体   English

MongoDB - findOne 不返回空值

[英]MongoDB - find returns empty where findOne does not

I'm tearing my hair out, trying to write a simple query in MongoDB Application Services, which I believe uses Mongoose in Node.js.我正在焦头烂额,试图在 MongoDB 应用程序服务中编写一个简单的查询,我相信它在 Node.js 中使用了 Mongoose。

I have a simple collection with Users , and I'm trying to find a set of users.我有一个简单的Users集合,我正在尝试find一组用户。

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.但是,将findOne切换为find不会打印任何用户,这不是预期的。 (ref db.collection.find() and querying documents ) (参考db.collection.find()查询文档

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删除asyncawait ,这使得findfindOne都返回一个空的 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:find中嵌入 function ,这在我找到的文档中没有讨论,但在一些堆栈溢出问题( 示例)中进行了讨论,这样做:
// 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我尝试使用runCommand但出现TypeError: 'runCommand' is not a function

This does not look like Mongoose, it looks like the regular Node.js Mongo driver.这看起来不像 Mongoose,它看起来像常规的 Node.js Mongo 驱动程序。

Which would return a cursor object from find() , as shown in the documentation here .这将从find()返回 cursor object,如此处的文档所示

Please try请试试

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

Which would enumerate the cursor and return an array.这将枚举 cursor 并返回一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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