Reputation: 84
Basically, I'm trying to compare the user's answer for a question in a "null" or local MongoDB to a key in another MongoDB that was declared before.
I know that to get the _id of the declared MongoDB (the real databse) is to call this._id, which is evident when I run console log on the browser console.
But how can I retrieve the _id of the local MongoDB?
Thanks in advance for any help.
Here is the helper code:
Template.question.events({
"click .button": function(e){
e.preventDefault;
for (var i = 0; i < document.getElementsByName("choices").length; i++){
if (document.getElementsByName("choices")[i].checked){
var init = document.getElementsByName("choices")[i].value;
}
}
Answers.insert({answer: init});
if(Answers.find({answer: init}) === Quiz.find({_id: this._id}, {answer: init})){
console.log("The answers match.");
}
}
});
The last part of the code is me attempting to compare the answer field in the "Answers" DB, which is the local DB to the answers field in the Quiz DB, which is the declared, legitimate database.
Edit:
So I used user "gdataDan" suggestion and changed my code to include a function taking in the error and result parameters + I added an else statement to see if the event helper actually is functioning properly until the end:
Template.question.helpers({
title: function(){
return Quiz.find();
}
})
Template.question.events({
"click .button": function(e){
e.preventDefault;
for (var i = 0; i < document.getElementsByName("choices").length; i++){
if (document.getElementsByName("choices")[i].checked){
var init = document.getElementsByName("choices")[i].value;
}
}
var id = "";
Answers.insert({answer: init}, function(error, result){
if (error){
console.log("error: " + error);
} else if (result){
id = result;
}
})
if(Answers.find({_id: id}, {answer: init}) === Quiz.find({_id: this._id}, {answer: init})){
console.log("The answers match.");
} else {
console.log("Something went wrong.");
}
}
});
Turns out that console log prints "Something went wrong," even though the answers match between both databases. So I feel like the way I call the find function or the id's themselves don't match.
Edit#2:
I tried declaring the init variable outside the loop and tried using the $eq operator for MongoDB and still get the "Something went wrong" message in the console.
Upvotes: 1
Views: 128
Reputation: 384
collection.insert will return the ID if there is no error.
var id = ''
Answers.insert({answer: init},function(error,result){
if(error) console.log('error: ' + error);
if(result) id = result;
});
Upvotes: 1