[英]MongoDB.find() and MongoDB.findone() returns null everytime?
I have a nodejs server connected to a MongoAtlas db.我有一个连接到 MongoAtlas 数据库的 nodejs 服务器。 The nodejs server inserts data just fine into the collection, but whenever I attempt to find data it always ends up returning null.
nodejs 服务器将数据插入到集合中,但每当我尝试查找数据时,它总是最终返回 null。 I have one document in a "Users" collection in my test cluster.
我的测试集群的“用户”集合中有一个文档。 but even when I query for everything my results(res) turn up null.
但即使当我查询所有结果时,我的结果(res)也会出现 null。
function isUsernameTaken(userData)
{
connection.then(() =>{
const db = client.db("test");
console.log(db.collection('Users').find({}));
db.collection('Users').find({username:userData.username}, function(err,res){
console.log(res.length);
if(err)
{
throw err;
}
if(res[0])
{
return true;
}else
{
return false;
}
});
})
}
This code is one of my functions that involve db.collection.find
, but for all the other functions I have essentially the same query and no luck.这段代码是我涉及
db.collection.find
的函数之一,但对于所有其他函数,我基本上有相同的查询并且没有运气。 Something else I tried were to query the exact document from inside the collection( id
, username
, password
) but once again no luck.我尝试的其他方法是从集合中查询确切的文档(
id
、 username
、 password
),但又一次没有运气。
EDIT: res is not null or undefined, res just does not return any documents from my db.编辑: res 不是 null 或未定义, res 只是不从我的数据库返回任何文档。
IMO, the async/await
syntax is so much easier to write, read, and deal with than the good old Promise and callback hell: IMO,
async/await
语法比旧的 Promise 和回调地狱更容易编写、阅读和处理:
async function isUsernameTaken(userData)
{
try{
const res = await db.collection('Users').findOne({ username: userData.username });
console.log(res);
return !!res; // Casts truthy/falsy value to boolean. This does in fact return a value from isUsernameTaken().
} catch(err) {
throw err;
}
}
And then you use it this way:然后你以这种方式使用它:
const isItTaken = await isUsernameTaken(someUserDataHere);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.