[英]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.