Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve single docs from MongoDB into javascript using mongoose?

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.

like image 349
Jadox Avatar asked Nov 30 '25 00:11

Jadox


1 Answers

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".

like image 84
Boris Serebrov Avatar answered Dec 03 '25 22:12

Boris Serebrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!