Reputation: 23
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.
Upvotes: 1
Views: 323
Reputation: 8091
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
.
Upvotes: 0
Reputation: 481
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.
Upvotes: 1
Reputation: 13669
try this way :
var memindex;
Manufacturer.findOne({name: result[key].name},function(err, resultarray) {
console.log("resultarray", resultarray);
memindex = resultarray;
});
Upvotes: 1