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"