user2947979
user2947979

Reputation: 35

Set variable equal to mongodb key value

var userLat = db.collection('users', function (err, document){
    document.findOne({_id: loggedUserID}, function(err, docs) {
       console.log(docs.currentUserLat);
    })
});

This is my code, I'm trying to get the value that's console logged into the variable. I just can't find the correct syntax to do this. The console log does return the correct value just need to drop it into the variable. Grateful for some help.

Upvotes: 0

Views: 806

Answers (2)

Dan J Miller
Dan J Miller

Reputation: 118

What do you want to do with 'docs.currentUserLat'?

You can do what you need to do without saving docs.currentUserLat to a variable that has scope outside of your db.collection call. Some examples:

If you simply want to change the document in your database, take advantage of the many methods specified in the Collections API: http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html. For example, to update the document and simultaneously resave it in the database:

db.collection('users', function (err, document){
    document.findOneAndUpdate({_id: loggedUserID},
        {currentUserLat: [updated value]},
        function(err, docs) {
            if(err) console.log(err);
        }
    )
});

If you just wanted to use docs.currentUserLat inside some node function, you'll need to properly nest the document.findOne function inside a callback (or vice versa). For example, to write currentUserLat to a file using the fs module:

var fs = require('fs');
db.collection('users', function (err, document){
    document.findOne({_id: loggedUserID}, function(err, docs) {
        fs.writeFile("pathToYourFile", docs.currentUserLat, function(err) {
            if(err) {return console.log(err);}
        });
    });
});

Or, if you want to send it in response to a simple http request:

var http = require('http');
http.createServer(function(request,response){
    db.collection('users', function (err, document){
        document.findOne({_id: loggedUserID}, function(err, docs) {
            response.writeHead(200,{'Content-Type':'text/html'});
            response.end(docs.currentUserLat);
        });
    });
});

The key thing to remember is what JohnnyHK said in their comment: docs.currentUserLat is only available inside the anonymous function passed to findOne. So, whatever it is that you need to do, do it inside this function.

(Reading the link JohnnyHK provided is a great way to get started with understanding asynchronous functions in Node. Another is https://github.com/rvagg/learnyounode)

Upvotes: 1

Salvador Dali
Salvador Dali

Reputation: 222869

First of all you have to understand how javascript callback works. After that you will see that nothing assigns docs.currentUserLat to your userLat variable. The reason behind this is that your docs.currentUserLat is available only inside the callback. Think about it in the following way:

You program started to execute and encountered the line: var userLat = .... This line tells: do a callback (which basically asks someone else to do the job), your while your job is being executed the program continues, by assigning userLat to undefined and executes further. Then at some period of time callback finishes and console.log your docs.currentUserLat.

One way to have the desired behavior is to make userLat global and instead of console.log(docs.currentUserLat); do userLat = docs.currentUserLat. The problem that if you will do this, your userLat eventually will have the desired value (if callback will not fail), but you can not predict when. So if you will do

var userLat = db.collection('users', function (err, document){ ... });
.. some other code
console.log(userLat);

you will not be sure that you will get the output. Another way to do put everything in another callback.

Upvotes: 0

Related Questions