简体   繁体   中英

Access variable outside mongoose find method - node js

In my node js program, I look into my mongoose database, and find and return the values in that collection - there is only one value.

var myValueX;
myCollection.find(function(err, post) {
        if (err) {
            console.log('Error ' + err)
        } else {
            myValueX = post[0].valuex;
        }
    });

console.log('Have access here' + myValueX);

Now, I want to be able to use myValueX outside this find method. How can I do this?

When I try the console.log above, I get undefined back - is this possible to achieve

To access myValueX after it had been assigned in find 's callback, you have two options, the first (naturally) is inside the callback itself, or inside a function called by the callback to which you send myValueX as an argument.

The better solution in my opinion is to use promises.

A simple promise-using solution is as follows:

function findPromise(collection) {
    return new Promise((resovle, reject) => {
        collection.find((err, post) => {
            if (err)
                return reject(err)

            // if all you want from post is valuex
            // otherwise you can send the whole post
            resolve(post[0].valuex)

        })
    })
}

findPromise(collection)
    .then((valueX) => {
        // you can access valuex here
        // and manipulate it anyway you want
        // after it's been sent from the `findPromise`
        console.log("valueX: ", valueX)
    })
    .catch((err) => {
        console.log("An error occurred. Error: ", err)
    })

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