![](/img/trans.png)
[英]MongoDB.find() and MongoDB.findone() returns null everytime?
[英]MongoDB - find returns empty where findOne does not
我正在焦頭爛額,試圖在 MongoDB 應用程序服務中編寫一個簡單的查詢,我相信它在 Node.js 中使用了 Mongoose。
我有一個簡單的Users
集合,我正在嘗試find
一組用戶。
在測試中,這會按預期打印單個用戶:
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"')
但是,將findOne
切換為find
不會打印任何用戶,這不是預期的。 (參考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"')
我試過:
async
和await
,這使得find
和findOne
都返回一個空的 objectfind
中嵌入 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);
});
兩者都導致
> ran at 1672323629660
> took 273.490161ms
> result:
"Done"
> result (JavaScript):
EJSON.parse('"Done"')
runCommand
但出現TypeError: 'runCommand' is not a function
這看起來不像 Mongoose,它看起來像常規的 Node.js Mongo 驅動程序。
這將從find()
返回 cursor object,如此處的文檔所示。
請試試
alarmingSubjs = await user_col.find().toArray();
這將枚舉 cursor 並返回一個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.