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

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3095b-e276.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3095b-e276.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?