Check if document exists in mongodb using es7 async/await

后端 未结 1 894
悲&欢浪女
悲&欢浪女 2021-02-04 11:17

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 us

1条回答
  •  攒了一身酷
    2021-02-04 11:36

    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.

    0 讨论(0)
提交回复
热议问题