简体   繁体   中英

How to use async-await in findOneAndUpdate

i tried following code to - find a name and replace same with another name in database and count and print the number of documents who have age of 30

const findAndUpdate = async (name, age) => {
    const user = await User.findOneAndUpdate({name})
    const count = await User.countDocuments({age})
    return count
}

findAndUpdate('oldName', 'newName', 30).then(count => {
    console.log(count)
}).catch(e => {
    console.log(e)
})

You are using it fine. Async/await works like this. You have a function that performs a task but you don't want to wait till it completes the task before it can continue another task.

Then you use the async statement to show it is a asynchronous function then you use the await when you want to perform a task that returns data so that it doesn't block the other tasks.

the problem is you are calling findAndUpdate expecting it to return a promise, if you want to use .then to get the count your function has to return a promise

const findAndUpdate = (name, age) => {
    return new Promise(async (resolve, reject) => {
        try {
            const user = await User.findOneAndUpdate(...)
            const count = await User.countDocuments(...)
            resolve(count)
        } catch (err) {
            reject(err)
        }
    })
}
findAndUpdate(...).then(count => {
    console.log(count)
}).catch(e => {
    console.log(e)
})

Looks like you are not providing the newName to the User.findOneAndUpdate() . You could fix it like so:

const findAndUpdate = async (oldName, newName, age) => {
    const user = await User.findOneAndUpdate({name: oldName}, {name: newName})
    const count = await User.countDocuments({age})
    return count
}

findAndUpdate('oldName', 'newName', 30).then(count => {
    console.log(count)
}).catch(e => {
    console.log(e)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM