0

I'm building a website that lets people write sticky notes and print it to them on the screen. I want to store the sticky notes inside a mongoDB with a db called stickyNotes and a collection called stickyNotes which currently has two documents.

I have a variable called stickyNotes which suppose to get the documents from the stickyNotes collection on the db but when I use the collection.find.toArray from the mongodb library to enter the documents to the stickyNotes variable in an asynchronous way, it shows an empty array value.

This is my server.js file:

const express = require("express");
const mongo = require("mongodb").MongoClient;
const app = express();

let stickyNotes = [];

//mongodb get all sticky notes
const mongoUrl = "mongodb://localhost:27017";
mongo.connect(mongoUrl, { useNewUrlParser: true }, async function(
  err,
  connection
) {
  if (err) {
    console.error(err);
  } else {
    console.log("Succesfully connected to the database");
    const db = connection.db("stickyNotes");
    const stickyNotesCollection = db.collection("stickyNotes");
    stickyNotes = await stickyNotesCollection.find({}).toArray();
  }
  connection.close();
});

console.log(stickyNotes);

app.use(express.static("./src/public"));

app.get("/sticky-notes", (req, res) => {
  console.log("Got a request for sticky notes");
  res.json(stickyNotes);
});

const port = 3000;
app.listen(port, () => {
  console.log(`App is running on port ${port}`);
});

halfer
  • 19,824
  • 17
  • 99
  • 186
nadav atar
  • 135
  • 1
  • 4
  • 9
  • 1
    `console.log(stickyNotes)` is logging empty array because it's executing before the query. Here the DB query is asynchronous. Other than that your script is working fine. Check out https://blog.risingstack.com/node-hero-async-programming-in-node-js to understand nodejs asynchronous behaviour – Subbu Jul 06 '19 at 16:52
  • Just put the `console.log()` inside the `async function`, after you `await`ed the `toArray()` promise - not outside of the `connect` function. – Bergi Jul 06 '19 at 18:37
  • Possible duplicate of [Node.js MongoDB collection.find().toArray returns nothing](https://stackoverflow.com/questions/45118957/node-js-mongodb-collection-find-toarray-returns-nothing) – Yilmaz Jul 06 '19 at 18:43
  • @Bergi I tried to do this indise the async function after the await and it still shows stickyNotes is an empty array... – nadav atar Jul 06 '19 at 19:08

1 Answers1

0

Can try with:

stickyNotesCollection.find({}, (err, result) => {
    if (err) throw err;
    stickyNotes = result;
  });

or find result in array:

collection.find().toArray(function(err, result) {
    console.log(result);
});

or iterate:

collection.find().each(function(err, result) {
    //once result
});
Matteo Ponzo
  • 47
  • 1
  • 3