0

I'm trying to fetch all the data from my collection called "users" and all i'm getting back is undefined.

In my folder and file named leaderboard/lb.js, and yes, my database is called collections:

const mongoose = require("mongoose");

let out = {};

mongoose.connect(`mongodb+srv://ramoth123:${process.env.MONGOPASS}@ramfish-bot-mgpji.mongodb.net/collections?retryWrites=true&w=majority`, { useNewUrlParser: true }, function(err, db) {

    if (err) throw err;
    //let dbo = db.db("collections");
    db.collection("users").find({ xp: Number }).toArray(function(err, result) {
      if (err) throw err;
      out.users = result;     
      db.close();
    });

});                             



function leaderboardUsersRaw() {
  return out.users
}

module.exports = leaderboardUsersRaw

In my database collection named "users"

In my server.js file:

app.get("/leaderboard", (req, res) => {
  const leaderboardFile = require("./leaderboard/lb.js")

  let users = leaderboardFile()

  console.log(users)


  res.send(users)
})

What am i doing wrong???

EDIT: Now it's working but after i load it 2 times, tf is this?

ramoth
  • 1
  • i think you have to call the function after the data is filled in var by mongodb response.use callback function for that OR promise function. – Dhamik jagodana Oct 13 '19 at 16:06

1 Answers1

0

Your database query is asynchronous so your function is returning the users before the query has completed.

You can try using async-await.

Try this:

** leaderboard/lb.js**

const mongoose = require("mongoose");

async function leaderboardUsersRaw() {
  const db = await mongoose.connect(`mongodb+srv://ramoth123:${process.env.MONGOPASS}@ramfish-bot-mgpji.mongodb.net/collections?retryWrites=true&w=majority`, { useNewUrlParser: true });

  const users = await db.collection("users").find({ xp: Number });

  const result = users.toArray();

  db.close();

  return result;
}

module.exports = leaderboardUsersRaw;

server.js

const leaderboardFile = require("./leaderboard/lb.js");

app.get("/leaderboard", async (req, res) => {
  try {
    let users = await leaderboardFile();

    res.send(users);
  }
  catch(err) {
    // Handle error
  }
});

I hope this helps.

Steve Holgado
  • 11,508
  • 3
  • 24
  • 32