0

I am making a poll app where on /createpoll you can fill in a new question and answer possibilities. On the index page you can vote on the poll. The live updates are done using Primus (websocket).

The live.js file I use works as a hub to pass data and cause events to trigger (eg. voting on the poll so everyone can see the updates live).

When I connect to the index page, I would like to show the latest poll from the mongodb online database collection. I have written the query and get a document returned. However, the variable I save the query in returns undefined when console.logged or passed through to the index page where I want to put it into the html.

Main question: how do I store the value without key into a variable?


I have tried to stringify, parse, ... but all come back with errors.


// the connection works, uri details are at the top of the file, but I 
// won't include for safety. I can see the data getting stored.

mongoose.connect(uri, { useNewUrlParser: true})

  .then((conn)=>{
  let modelConn = conn.model ('poll', pollSchema);

  let question = modelConn.findOne({},'question', {projection:{question:1, _id: 0}},function(err,obj) { console.log(obj); }).sort([['_id', -1]]);

  let answer1 = modelConn.findOne({},'answer1', {projection:{answer1:1, _id: 0}}, function(err,obj) { console.log(obj); }).sort([['_id', -1]]);

  let answer2 = modelConn.findOne({},'answer2', {projection:{answer2:1, _id: 0}}, function(err,obj) { console.log(obj); }).sort([['_id', -1]]);

  primus.write({
    "action": "showDbPoll",
    "question": question,
    "answer1": answer1,
    "answer2": answer2
  });


})
  .catch((errorMessage) => {
  console.log(errorMessage);
});
// console output from nodemon

{ question: 'a question' }
{ answer1: 'answer 1' }
{ answer2: 'answer 2' }


I want the value of the document to be saved into a variable so I can pass it on to the next page. So my variable should be equal to this string: "a question"

1565986223
  • 6,420
  • 2
  • 20
  • 33

2 Answers2

0

Returning from callback won't work. You can use async..await like:

async function someFunc(uri) {
  try {
    const conn = await mongoose.connect(uri, { useNewUrlParser: true});
    const modelConn = conn.model ('poll', pollSchema);
    // not sure why you're using sort so skipped it
    // maybe something like this ? https://stackoverflow.com/questions/13443069/mongoose-request-order-by
    // .findOne({}, 'question', {sort: { _id: -1 }, projection:{ question:1, _id: 0 } });
    const question = await modelConn.findOne({},'question', {projection:{question:1, _id: 0}});
    const answer1 = await modelConn.findOne({},'answer1', {projection:{answer1:1, _id: 0}});
    const answer2 = await modelConn.findOne({},'answer2', {projection:{answer2:1, _id: 0}});

    primus.write({
      "action": "showDbPoll",
      "question": question,
      "answer1": answer1,
      "answer2": answer2
    });
  } catch (e) {
    // handle error
    console.error(e)
  }
}
someFunc(uri)
1565986223
  • 6,420
  • 2
  • 20
  • 33
  • This works! :D Thank you very much! Been stuck on this assignment for 2 weeks! The reason I use sort is to get the latest poll from the database. That way if people browse to the website, they will get to see the last poll that was made :) – Annelies Bellon Apr 24 '19 at 16:57
0

There is no need in making 3 requests to database and also projection and sorting can be avoided. Try this code:

mongoose.connect(uri, { useNewUrlParser: true})

  .then(async (conn) => {
  const modelConn = conn.model('poll', pollSchema);

  const { question, answer1, answer2 } = await modelConn.findOne({});

  primus.write({
    "action": "showDbPoll",
    "question": question,
    "answer1": answer1,
    "answer2": answer2
  });
})
  .catch((errorMessage) => {
  console.log(errorMessage);
});
Ilarion Halushka
  • 2,083
  • 18
  • 13