Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Annelies Bellon
1,316 PointsMongoose + NODEJS: my findOne query returns documents but I need the values without keys
I am working on a poll app where I use Primus for my websocket to have live updates in my voting system. I work with two separate pages. So on one page you fill in the poll and answers and this saves to the database and redirects to the actual voting page. On the voting page I want to load the question and answers from the mongodb online database. My connection works and I get documents but I don't know how to get the values out of them. The primus write part is to pass my data to my page from my live.js file. This currently reads the data as u defined. This is my query/connection code:
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
});
//console.log(object);
})
.catch((errorMessage) => {
console.log(errorMessage);
});
My output in nodemon:
{ question: 'a question' } { answer1: 'answer 1' } { answer2: 'answer 2' }
1 Answer
Ken Alger
Treehouse TeacherAnnelies;
Have you tried using dot notation? Something like obj.question or obj.answer1?
Ken
Annelies Bellon
1,316 PointsAnnelies Bellon
1,316 PointsI did, but it turns out I needed to use async await to get the data from the collection. This is the code I ended up with which now works: