简体   繁体   中英

MongoDB findOne() returns value in the function but doesn't return the value in node

So I'm trying to assign values from MongoDB in node with a function. My problem is, it finds the data but it returns undefined outside of the findOne function.

Code:

async function findFile(userid) {

    let ufile = mCollection.findOne({"uid": userid}, function(err, res) {
        console.log(res);
        return res;
    });

    console.log(ufile);

};

findFile(authId);

Results: Console log

You are returning inside the callback. This means that mCollection.findOne itself doesn't return any value.

What you can do instead is log the value inside the callback like so:

async function findFile(userid) {

    let ufile = mCollection.findOne({"uid": userid}, function(err, res) {

        console.log(ufile);

    });


};

findFile(authId);

Or run the function as a promise, and await it:

async function findFile(userid) {

    let ufile = await mCollection.findOne({"uid": userid});
    console.log(ufile)

};

findFile(authId);

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