0

I'm trying to return a MongoDB Query as a JSON Object so it can be stored in a javascript variable and used as need. I have the query executing fine but I can't get it to store as a JSON object and I keep getting this error Unexpected token u in JSON at position 0. I've looked it up and seen other people having this problem but I tried their solutions and I couldn't get it to work. Please help me.

Here's the user.js model code:

module.exports.example = function() {
    var query = User.find({}).lean().exec(function (err, users) {
        return JSON.stringify(users);
    });
}

and here's my express routes file:

router.get('/everything', function (req, res) {
    var q = User.example();
    var x = JSON.parse(q);
    console.log(x);
});
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
MrShedford
  • 137
  • 1
  • 2
  • 12
  • The `u` is the first character in `undefined` because you return `undefined` from the `example` function. – Quentin Jun 26 '17 at 12:42
  • There is a bad blog post out there I am sure. You all need to stop using `module.exports` for what you should be defining as a ["static method" as defined in the mongoose documentation](http://mongoosejs.com/docs/guide.html). Then also learn to return the `Promise` as in `User.find({}).lean().then( x => console.log(x))` – Neil Lunn Jun 26 '17 at 13:28

0 Answers0