我有一个格式为 json 的对象 -
{
'Which is the Capital of India ? ': {
'Delhi': 1,
'Bangalore': 0,
'Mumbai': 0,
'Chennai': 0
}
}
我正在尝试用 Mongoose 为这个对象编写模式。我已经写了 -
exports.quiz = mongoose.Schema({
question: {
answer: Boolean
}
});
由于我是 mongodb 和 mongoose 新手,我需要知道这是否是正确的方法?
最佳答案
这不是一个很好的对象表示。将“对象”视为数据容器的通用形式。您在 JSON 表单中指定的所有“键”实际上都是“数据”点,并且应该这样对待。
此外,为了获得最佳性能,您希望将其嵌入数据,因为这样就会对 MongoDB 进行单一读取和写入。这就是为什么您应该使用 MongoDB,而不是尝试以关系方式对其进行建模。
所以一个好的通用模式应该是这样的:
// Initial requires
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// A generic answer sub-schema
var answerSchema = new Schema({
answer: String,
correct: Boolean
});
// A generic Question schema
var questionSchema = new Schema({
text: String,
answers: [answerSchema]
});
exports.Question = mongoose.model( 'Question', questionSchema );
MongoDB 中的序列化形式基本上是这样的:
{
"text": "Which is the Capital of India",
"answers": [
{ "answer": "Delhi", "correct": true },
{ "answer": "Bangalore", "correct": false },
{ "answer": "Mumbai", "correct": false },
{ "answer": "Chennai", "correct": false }
]
}
从当前的 JSON 进行转换不是问题:
var orig; // Your existing structure
var data = {};
Object.keys(orig).forEach(function(title) {
// Really only expecting one top level key here
// Stripping out the common formatting
var fixed = title.replace(/\s+\?\s+$/,"");
data.text = fixed;
data.answers = [];
// Loop the answer keys
Object.keys(orig[title]).forEach(function(answer) {
data.answers.push({
answer: answer,
correct: (orig[title][answer]) ? true : false
});
});
Question.create( data, function(err,question) {
if (err) throw err;
console.log("Created: %s", question );
});
});
但是请研究异步循环控制,以找到一种更好的方法来通过大量“问题”列表来实现此目的。
因此通用结构为您提供了一些不错的选择:
您可以添加架构对象固有的一些格式化逻辑,例如以一致的方式格式化问题。因为我们去掉了尾随的空格和“?”问号。从您的数据中删除,可以通过方法和自定义序列化添加。
Answers 是一个数组,因此您可以“打乱”顺序,这样可能的答案并不总是以相同的顺序出现。
嵌入数组项的另一个巧妙之处(特别是考虑到最后一点)是 mongoose 默认情况下将为每个数组元素分配一个唯一的 _id
字段。这使得检查答案变得容易:
Question.findOne(
{
"_id": questionId,
"answers": { "$elemMatch": { "_id": anwerId, "correct": true } }
},
function(err,result) {
if (err); // handle hard errors
if (result != null) {
// correct
} else {
// did not match, so got it wrong
}
}
);
这就是“通用”服务器端响应处理程序的核心,它本质上需要有效负载中的两个参数,即当前的 questionId
和提交的 answerId
。当 .findOne()
操作的结果与文档不匹配并且响应为 null
时,则答案不正确。
这意味着您可以在架构定义中添加更多“糖”。这里使用一点“蛮力”(例如),您可以从发送给客户端的答案中删除“正确”的键,并执行一些其他格式设置。在主要架构定义之后:
// Fisher Yates shuffle
function shuffle(array) {
var counter = array.length,
temp,
index;
while (counter > 0) {
index = Math.floor(Math.random() * counter);
counter--;
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
if (!answerSchema.options.toJSON) answerSchema.options.toJSON = {};
answerSchema.options.toJSON.transform = function(doc,ret,opts) {
// Pulling the "correct" markers from the client response
delete ret.correct;
};
if (!questionSchema.options.toJSON) questionSchema.options.toJSON = {};
questionSchema.options.toJSON.transform = function(doc,ret,opts) {
// Add the formatting back in
if ( ret.hasOwnProperty('text') )
ret.text = doc.text + " ? ";
// Shuffle the anwers
ret.answers = shuffle(doc.answers);
};
exports.Question = mongoose.model( 'Question', questionSchema );
这为您提供了一个很好的打包和“隐藏数据”响应,可以发送到客户端进行显示:
{
"text": "Which is the Capital of India ? ",
"_id": "5450b0d49168d6dc1dbf866a",
"answers": [
{
"answer": "Delhi",
"_id": "5450b0d49168d6dc1dbf866e"
},
{
"answer": "Chennai",
"_id": "5450b0d49168d6dc1dbf866b"
},
{
"answer": "Bangalore",
"_id": "5450b0d49168d6dc1dbf866d"
},
{
"answer": "Mumbai",
"_id": "5450b0d49168d6dc1dbf866c"
}
]
}
总体来说:
更好的 MongoDB 建模方法
简单的一次查询读取和响应检查
使用自定义序列化逻辑向客户端隐藏数据。
您可以做一些很好的事情来很好地扩展并将逻辑放在需要的地方。
关于javascript - Mongoose 具有 JSON 数据,其值作为属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26624230/