[英]How to write an asynchronous for-each loop in Express.js and mongoose?
[英]How to store an array with Mongoose + Express.js?
我是MongoDB的新手,我想存储一个数组。
这是我想要的例子
question : {
question : "My question",
answer : "My answer",
subQuestions :
[0] {
question: "My sub question",
answer : "My sub answer"
},
[1] {
question: "My other sub question",
answer : "My other sub answer"
}
}
但是我没有成功在subQuestions中放置多个条目。 我得到了这个:
question : {
question : "My question",
answer : "My answer",
subQuestions : {
question {
[0] : "My sub question",
[1] : "My other sub question"
},
answer {
[0] : "My sub answer",
[1] : "My other sub answer"
}
}
}
我实际上很难在前面处理这些东西,我真的很想拥有我在第一集团中所展示的东西。
这是我的实际架构:
var Questions = new Schema({
question: { type: String },
answer : { type: String },
subQuestions : {
question : [String],
answer : [String]
}
});
还有我的保存脚本:
var q = new Questions;
q.subQuestions.question = ["My sub question", "My other sub question"];
q.subQuestions.answer = ["My sub answer", "My other sub answer"];
q.save(function(err){
console.log(err);
});
有人可以帮我弄这个吗 ? 我已经有一段时间了,所以也许这只是我没想到的一件事。
预先非常感谢您,不要犹豫,问我问题。
您只需要在模式中定义一个数组:
var Questions = new Schema({
question: { type: String },
answer : { type: String },
subQuestions : [{
question : String,
answer : String
}]
});
请注意,我更改了花括号。
要添加一个新的子问题,可以使用push() :
q = new Questions
sq.question = "How are you doing?"
sq.answer = "Great."
q.subQuestions.push(sq)
我没有测试此代码,但它首先从两个字符串(这是sq
对象)组装了一个JavaScript对象,然后将其推入数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.