简体   繁体   中英

how to execute mongoose query in nodejs

I'm new to nodeJS and JS.

I'm need to fetch data from mongoose collection using findone and wanted to store in a variable. Below code is storing value in resultarray but not in memindex . Not sure how to store in memindex .

memindex = Manufacturer.findOne({name: result[key].name}, function(err, resultarray) {
console.log("resultarray", resultarray);});

The reason why I need value in memindex is, I need to use this in another condition.

try this way :

var memindex;

Manufacturer.findOne({name: result[key].name},function(err, resultarray) {
    console.log("resultarray", resultarray);
    memindex = resultarray;
});

Use functions instead of mutating globals :

const memindex = await Manufacturer.findOneAsync({name: result[key].name});

This being an async function you might want to consider promises dwelling into Promises and/or async/await.

Setting asside the other two answers for the moment which for some reason ask you to change how you assign variables..

Your initial code is almost there. Just in your callback function, you are not returning the results from the query.

memindex = Manufacturer.findOne({name: result[key].name}, function(err, resultarray) {
    console.log("resultarray", resultarray);
    return resultarray;
});

In the first param of findOne is your search filter, the second is the function that will be called when a response is complete. In this example we return the data to the caller, which in this case is memindex .

findOne Reference

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