Check if document exists in mongodb using es7 async/await

浪子不回头ぞ 提交于 2019-12-02 23:29:21
Denis Yakovenko

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();
    }
}

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); inside of another function declared async.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!