1

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.

3 Answers 3

1

try this way :

var memindex;

Manufacturer.findOne({name: result[key].name},function(err, resultarray) {
    console.log("resultarray", resultarray);
    memindex = resultarray;
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

In the previous answer. Instead of globally initialising a variable and then mutating its value inside the function, use a function itself to return the data and assign it.
Yes i know, but as pointed out by OP that he is new to JS, he might not have context of mongoose's promises and asynchrnocity in general. This is general answer for assigning a value returned from a function.
This revision is a nicer answer as it offers a different solution. +1
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.