3

I'm trying to get a single document from a mongodb collection and use that document as an object in javascript. The problem is that the json that I need to store it as a plain object in javascript only comes when I call it from a response.json(doc) and I can't access that doc outside the function. All the info I found is so confusing!

Is it possible to have something like this:

var a = mongoose.model('collectionName').findOne() //etc.

Just get the whole document and transform it into a javascript object accessible in the global scope, so I can get properties from a whenever I please.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
Jadox
  • 157
  • 1
  • 1
  • 7

2 Answers2

1

It sounds like you have a problem with node.js callbacks. This is not only with mongoose, but any code you write for node.js will look like this:

app.get('/users', function (req, res) {
    Model.find({}, function (err, docs) {
        res.json(docs);
    });
});

So you just nest the callbacks until you have everything you need to send the response.

You need to get used to this style of programming. Once you are comfortable with this, you will notice that sometimes the nesting becomes too deep (callback hell).

And there are solutions to that - split your callbacks into individual functions or use async, promises, es6 generators.

But first, you need to understand the way it is done "naturally".

Community
  • 1
  • 1
Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54
0

A primary concept of NodeJS (and therefore using MongoDB with it) is the async nature of the code you are writing. Any queries you make to your database will happen asynchronously to the rest of your code's execution. For this reason, you will need to pass a callback function with your query so that when the query is completed, your callback function will be executed. Any variables you want to assign to the result of your query should be done in that callback.

For example:

mongoose.model('collectionName').findOne( { ' some query here' }, function(err, doc) {
    // set some variable to the 'doc' result if you want
    // put any logic here to handle the result
});

Any code you put inside the callback method will be executed when the query completed. So you should always check for the existence of an error before doing anything with the resulting document(s).

Mike
  • 10,297
  • 2
  • 21
  • 21