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}`);
});

4
  • 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 blog.risingstack.com/node-hero-async-programming-in-node-js to understand nodejs asynchronous behaviour Commented Jul 6, 2019 at 16:52
  • Just put the console.log() inside the async function, after you awaited the toArray() promise - not outside of the connect function. Commented Jul 6, 2019 at 18:37
  • Possible duplicate of Node.js MongoDB collection.find().toArray returns nothing Commented Jul 6, 2019 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... Commented Jul 6, 2019 at 19:08

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer, I tried it and when I console.log() stickyNotes after the query executes it shows alot of metadata which I believe is a MongoDB Cursor, you have any idea how to fix it?
I changed the answer
I tried all of those and the first two didnt work and the last one said "Cursor each is deprecated, use cursor ForEach". Any idea?
stickyNotesCollection.find().forEach((result) => { /*result*/ }, (err) =>{ /*error*/ });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.