使用es7 async/await检查mongodb中是否存在文档 [英] Check if document exists in mongodb using es7 async/await
问题描述
我试图检查提供了email
的用户是否存在于集合users
中,但是我的函数始终为每个调用返回未定义的内容.我使用es6和async/await
来摆脱很多回调.这是我的功能(在类的内部):
I'm trying to check if the user with the email
provided exists in the collection users
, but my function keeps returning undefined for every call. I use es6 and async/await
in order to get rid of lots of callbacks. Here's my function (it is inside of a class):
async userExistsInDB(email) {
let userExists;
await MongoClient.connect('mongodb://127.0.0.1:27017/notificator', (err, db) => {
if (err) throw err;
let collection = db.collection('users');
userExists = collection.find({email: email}).count() > 0;
console.log(userExists);
db.close();
});
console.log(userExists);
return userExists;
}
因此,在.connect
调用内的第一个console.log
总是返回false
,因为.find
的返回值不是数组,而是一个看起来像这样的巨大对象:
So, the first console.log
inside the .connect
call always returns false
because the returned value of the .find
is not an array, it is some huge object which looks like this:
{ connection: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'notificator.users',
cmd:
{ find: 'notificator.users',
limit: 0,
skip: 0,
query: { email: 'email@example.com' },
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: undefined } },
options:
........
........
最后一个console.log
总是不确定的(尽管我认为不应该这样,因为await
等待异步调用的结束,对吧?)
And the last console.log
is always undefined (although I think it shouldn't be like that, because await
waits for the end of the asynchronous call, right?)
我只需要函数即可返回布尔值,而不是Promise
之类的东西.
I just need my function to return a boolean value, not a Promise
or something.
有人可以帮我吗?
console.log(collection.findOne({email: email}));
会返回以下内容:
{ 'Symbol(record)_3.ugi5lye6fvq5b3xr':
{ p: [Circular],
c: [],
a: undefined,
s: 0,
d: false,
v: undefined,
h: false,
n: false } }
更新2
似乎是由于我对es7 async/await
的了解不足而引起的问题.
UPDATE 2
Seems like it was the issue with my poor knowledge of es7 async/await
.
现在.connect
中的代码将返回所需的值.
Now the code inside the .connect
returns the needed value.
async userExistsInDB(email) {
let userExists;
await* MongoClient.connect('mongodb://127.0.0.1:27017/notificator', async(err, db) => {
if (err) throw err;
let collection = db.collection('users');
userExists = await collection.find({email: email}).limit(1).count() > 0;
db.close();
});
console.log(userExists); // <--- this is not called at all
return userExists;
}
但是,现在完全不执行console.log
或.connect
调用之后的任何操作.
However, now the console.log
or anything after the .connect
call is not performed at all.
现在,每次我在某个地方调用userExistsInDB()
函数并console.log
其结果时,我都会得到:
Now, every time I call the userExistsInDB()
function somewhere and console.log
its result, I get this:
{ 'Symbol(record)_3.78lmjnx8e3766r':
{ p: [Circular],
c: [],
a: undefined,
s: 0,
d: false,
v: undefined,
h: false,
n: false } }
有什么想法为什么会这样?
Any ideas why it is like that?
推荐答案
好的,这就是我的工作方式:
Ok, here's how I got it working:
async function userExistsInDB(email, password) {
let db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator');
try {
let collection = db.collection('users');
let userCount = (await collection.find(
{
email: email,
password: password
}).limit(1).count());
return userCount > 0;
} finally {
db.close();
}
}
并且由于函数声明保证中的async
关键字返回的值将是Promise
,因此从该函数中获取实际返回结果的唯一方法是:
And because the async
keyword in function declaration guarantees that the returned value will be a Promise
, the only way to get the real returned result out of this function is:
let result = await this.userExistsInDB(email, password);
在另一个声明为async
的函数中.
let result = await this.userExistsInDB(email, password);
inside of another function declared async
.
这篇关于使用es7 async/await检查mongodb中是否存在文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!