How can the data in the mongoose query table be saved?

function searchData(){
    NodeInfo.find({}, function(err, res){
        if(err) {
            console.log("Error:" + err);
        }
        console.log(JSON.stringify(res,null,2));  //1
        return res;
    })
}
let a = searchData();
console.log(a); //2

Why does print 1 show complete data and print 2 to tell undefined, how to save the found data to an array?

Mar.24,2022

because the query takes time, find is an asynchronous method, the second one executes console.log first, and the query is not completed when it is executed, and searchData itself does not return a value, so an is undefinded . The callback, that executes find only executes the first console.log, after the query is completed, so the first console.log can print out the results

.

mongoose should support promise, so you can write:

async function searchData(){
    try {
        return await NodeInfo.find({});
    } catch (err) {
        console.log("Error:" + err);
    }
}

clipboard.png

Menu