目前,我有一个mongo数据库,可以跟踪用户提交的答案。当用户为他们已经做过的答案输入输入时,是或否我想检查答案是否已经改变。问题是这只有半个工作时间。
下面我有一个名为Questions Service的sails服务,当用户向node.js服务器发送答案时,该服务从Questions Controller调用。
QuestionServer.js
var ObjectID = require('mongodb').ObjectID;
module.exports = {
submitAnswer: function(tokenKey, questionId, answer, done) {
User.findOne({tokenKey: tokenKey}).exec(function (err, findOneRecord){
if(findOneRecord) {
var qId = ObjectID(questionId);
QuestionsAnswered.findOrCreate({question: qId, user: findOneRecord.id}).exec(function createFindCB(error, createdOrFoundRecord){
if(error) {
done(error, findOneRecord, null);
}else if(createdOrFoundRecord){
var oldAnswerChanged = QuestionService.submitAnswerCheck(createdOrFoundRecord.answer, answer);
console.log("Old Changed Answer = " + oldAnswerChanged);
createdOrFoundRecord.answer = answer;
createdOrFoundRecord.save(function(saveErr) {
QuestionService.submitCount(questionId, answer, oldAnswerChanged, done);
});
}
});
}
});
},
submitAnswerCheck: function(recordAnswer, answer) {
console.log("recordAnswer = " + recordAnswer);
console.log("answer = " + answer);
recordAnswer = Boolean(recordAnswer);
answer = Boolean(answer);
if(recordAnswer != answer){
return true;
}
return false;
}
}
正如您在我的submitAnswerCheck函数中的代码中所看到的,我想确保传递给此函数的布尔值始终是基元而不是布尔对象。
您将在下面找到发送到服务器的所有控制台日志的输出。
关于以下输出的附加说明,更改!= to!==不会更改控制台的输出。下面的答案仍然是一样的。
输出到控制台:
recordAnswer = true
answer = true
Old Changed Answer = false
recordAnswer = true
answer = false
Old Changed Answer = false
recordAnswer = false
answer = false
Old Changed Answer = true
recordAnswer = false
answer = true
Old Changed Answer = true
recordAnswer = true
answer = true
Old Changed Answer = false
我希望看到的示例输出2和4对于“Old Changed Answer”都返回true,但似乎发生的事情是每当recordAnswer为false时,submitAnswerCheck总是返回true。
最后这里是将布尔值保存到mongodb的模型:
QuestionsAnswered.js
module.exports = {
attributes: {
question: {
model: "question",
required: true
},
user: {
model: "user",
required: true
},
answer: {
type: "boolean",
boolean: true
}
}
};
我不确定我是否想念布尔基元和布尔对象之间的区别,或者在我的模型中设置布尔值时是否还有其他的东西。在javascript / sails.js中比较boolean时有其他人遇到过这个问题吗?
答案 0 :(得分:0)
发现问题
第一关,因为这个article解释使用布尔函数是非常危险的,因为事实证明JavaScript对类型强制非常积极。这意味着您无法在布尔函数上进行中继,以将变量转换为基元。
从此我发现Postman发送我的答案布尔值作为字符串示例:
module.exports = {
answer: function(req, res) {
var tokenKey = req.param("tokenKey");
var questionId = req.param("questionId");
var answer = (req.param("answer") == 'true');
QuestionService.submitAnswer(tokenKey, questionId, answer, function(err, yes, no){
return res.json({
countYes: yes,
countNo: no,
err: err
});
});
}
};
解决方案就像检查答案是否等于“真实”一样简单。如下图所示:
正确的方式(QuestionController.js):
module.exports = {
answer: function(req, res) {
var tokenKey = req.param("tokenKey");
var questionId = req.param("questionId");
var answer = req.param("answer");
QuestionService.submitAnswer(tokenKey, questionId, answer, function(err, yes, no){
return res.json({
countYes: yes,
countNo: no,
err: err
});
});
}
};
方式不正确:
{{1}}