Javascript 带有JSON数据的Mongoose,其值作为属性名
我有一个json对象,格式为-Javascript 带有JSON数据的Mongoose,其值作为属性名,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个json对象,格式为- { 'Which is the Capital of India ? ': { 'Delhi': 1, 'Bangalore': 0, 'Mumbai': 0, 'Chennai': 0 } } 我试图用mongoose为这个对象编写模式。我写过—— exports.quiz = mongoose.Schema({ question: { answer: Boolean } });
{
'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 );
});
});
但是,通过大量的“问题”列表,研究异步循环控制,寻找更好的方法
因此,通用结构为您提供了一些不错的选择:
- 您可以为schema对象添加一些固有的格式化逻辑,例如以一致的方式格式化问题。因为我们去掉了尾随的空格和“?”问号。可以通过方法和自定义序列化将其从数据中删除
- 答案是一个数组,因此您可以“洗牌”顺序,使可能的答案不总是以相同的顺序出现
\u 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建模的更好方法
- 简单的一次查询读取和响应检查
- 使用自定义序列化逻辑对客户端隐藏数据
你可以做一些很好的事情,可以很好地进行扩展,并将逻辑放在需要的地方。你需要在某个时候调用
.model()
,是的,我知道这一点,我在我的路线中调用它(我使用的是express)。但是模式声明正确吗?如何设计表单来保存这种类型的嵌套数据。请看一下我的另一个问题-非常感谢你的帮助