2015-07-11 47 views
0

我是MongoDB和AngularJS的新手,不幸的是我不知道如何搜索我的問題。 我有這樣一個模式:用MongoDB和AngularJS存儲和顯示JSON數據

var QuestionSchema = new Schema({ 
    "categoryID": Number, 
    "questionString": String, 
    "answerA" : String, 
    "answerB" : String, 
    "answerC" : String, 
    "answerD" : String, 
    "correctAnswer": String, 
    "author": Number, 
    "isCertified": { 
     type: Boolean, 
     default: false 
    }, 
    "created": { 
     type: Date, 
     default: Date.now 
    } 
}); 

然後我想在一個表中顯示與AngularJS JSON數據:

<tr class="list" ng-repeat="q in questions"> 
    <td class="list">{{ q._id }}</td> 
    <td class="list">{{ q.categoryID }}</td> 
    <td class="list">{{ q.questionString }}</td> 
    <td class="list">{{ q.answerA }}</td> 
    <td class="list">{{ q.answerB }}</td> 
    <td class="list">{{ q.answerC }}</td> 
    <td class="list">{{ q.answerD }}</td> 
    <td class="list">{{ q.correctAnswer }}</td> 
    <td class="list">{{ q.author }}</td> 
    <td class="list"> 
</tr> 

我的JSON數據是這樣的:

{ 
    "questionString": "What is the sense of life?", 
    "categoryID: "2", 
    "author": "1", 
    "answerA": "I am answer A", 
    "answerB": "I am answer B", 
    "answerC": "I am answer C", 
    "answerD": "I am answer D", 
    "correctAnswer": "3" 
    } 

雖然這是有效的,但這不完全是我想要的。我想爲該類別和作者設置另一個集合,以便我可以執行類似{{ q.author.authorName }}{{ q.category.categoryName }}的操作,這些操作應根據其ID來顯示作者/類別名稱。存儲這種數據的最佳做法是什麼?

這將是巨大的定義是這樣的:

var categories = [ 
    {"catID": "1", "catString" : "General"}, 
    {"catID": "2", "catString" : "Games"}, 
    {"catID": "3", "catString" : "Movies"} 
]; 

另一個問題是:會有存儲答案以及相應的correctAnswer更好的辦法?

+0

你能分享你的對象嗎?粘貼您的完整對象。 – Vineet

+0

你的意思是JSON文件嗎? – sqe

+0

是的,你的json對象。它會幫助我調試 – Vineet

回答

0

這些似乎是mongodb中一對多關係的情況。你可以看一下鏈接:one-to-many

你必須創建一個作者集合和其他收藏品的它的id引用它:

例如:

{ 
    _id: 'authors' 
    author: [ "Kristina Chodorow", "Mike Dirolf"] 
} 

在貓鼬的情況下,可以使用ObjectId引用問題模式中的作者:

authors: { 
    type: Schema.ObjectId, 
    ref: 'authors' 
}