2014-10-27 94 views
1

我正在使用Node/Mongoose/MongoDB並試圖構建一個輪詢應用程序。一個關鍵的需求是跟蹤單個用戶對同一輪詢的響應如何隨着時間的推移而變化(他們會一遍又一遍地進行相同的輪詢)。Mongoose JS:在一個文檔中創建一個引用到另一個文檔中的嵌入文檔

我有一個用戶模式:

var UserSchema = new Schema({ 
    ... 
}) 

我嵌入我的調查文件的問題,因爲我幾乎總是當我要求調查需要的問題。

var QuestionSchema = new Schema({ 
    text: { type: String, required: true } 
}) 

var PollSchema = new Schema({ 
    name: { type: String, required: true }, 
    questions: [QuestionSchema] 
}) 

module.exports = mongoose.model('Poll', PollSchema); 

// Know this is unnecessary, but read the following to see why I'm doing this 
module.exports = mongoose.model('Question', QuestionSchema); 

這裏是我的困惑:

我的用戶將在同一調查中多次服用。因此,我創建了一個「答案歷史」,其中包含每個用戶對投票中單個問題的「答覆」。

我不明白如何做的是創建從一個文檔到另一個文檔中的嵌入式文檔的參考。例如:

var AnswerSchema = new Schema({ 
    answer: { type: String, required: true }, 
    time: { type: Date } 
}) 

var AnswerHistorySchema = new Schema({ 
    user: { type: Schema.ObjectId, ref: 'User' }, 
    // I know this is wrong, but... 
    question: { type: Schema.ObjectId, ref: 'Question' }, 
    answers: [AnswerSchema] 
}) 

我在這裏錯過了什麼?

  • 是否需要引用投票調查,並記錄投票內的AnswerHistory應用於哪個問題?
  • 或者這是否意味着我不應該在投票文件中嵌入問題?
  • 其他我還沒想過的東西?

編輯:這是看問題更簡潔的方式:

var C = new Schema({...}); 
var B = new Schema({c: [C]}); 
var A = new Schema({c: { type: ObjectId, ref: 'B.c' }); 

回答

0

而是具有歷史模式,我寧願有投票的「版本」跟蹤用戶和答案。

每次用戶進行新的輪詢時,都會創建一個PollByUser對象。

讓我們說:

var PollByUserSchema = new Schema({ 
    user: { type: Schema.ObjectId, ref: 'User' }, 
    poll:{ type: Schema.ObjectId, ref: 'Poll' }, 
    taken:{ 
     type:Date, 
     default:Date.now 
    } 
}); 

module.exports = mongoose.model('PollByUser', PollByUserSchema); 

var AnswerSchema = new Schema({ 
    answer: { type: String, required: true }, 
    time: { type: Date }, 
    question: { type: Schema.ObjectId, ref: 'Question' }, 
    pollByUser: { type: Schema.ObjectId, ref: 'PollByUser' }, 

}) 

編輯:

var PollSchema = new Schema({ 
    name: { type: String, required: true }, 
    questions: [{ type: Schema.ObjectId, ref: 'Question' }] 
}) 
+0

感謝您的建議。我想我明白你對整體策略的意思,但我仍然有點困惑。我的理解是,我不能在AnswerSchema中使用ref:「Question」,因爲問題是Poll中嵌入的文檔。這不正確嗎? – 2014-10-27 23:14:29

+0

我得到了你,很好,我知道你不能,但你可以改變你的投票模式,只有問題ID的參考 – 2014-10-27 23:32:30

+0

嗯,那是我想要避免的一件事。如果沒有人建議避免這種情況,我會接受答案。謝謝! – 2014-10-28 11:27:51

相關問題