node.js - Mongoose JS : Create a reference in one document to an embedded document in another document

标签 node.js mongodb mongoose

我正在使用 Node/Mongoose/MongoDB 并尝试构建一个轮询应用程序。一个关键需求是跟踪单个用户对同一民意调查的响应如何随时间变化(他们一遍又一遍地进行同一民意调查)。

我有一个用户模型:

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);

这是我的困惑:

我的用户将多次进行同一项民意调查。因此,我正在创建一个“AnswerHistory”,其中包含单个用户对民意调查中单个问题的每个“答案”。

我不明白如何创建从一个文档到另一文档中嵌入文档的引用。例如:

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]
})

我在这里缺少什么?

  • 我是否需要改为引用民意调查,并跟踪答案历史记录适用于民意调查中的哪个问题?
  • 或者这是否意味着我不应该在投票文档中嵌入问题?
  • 还有什么我没有想到的吗?

编辑:这是查看问题的更简洁的方式:

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

最佳答案

我宁愿让民意调查的“版本”跟踪用户和答案,而不是历史模式。

每次用户进行新的民意调查时,您都会创建一个 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' }]
})

关于node.js - Mongoose JS : Create a reference in one document to an embedded document in another document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26590881/

相关文章:

javascript - angularjs - 发布数组的特定元素

mongodb - 查找数组字段不为空的 MongoDB 记录

node.js - Mongoose .save() -- TypeError : _this[i]. 发出不是一个函数

sockets - 多个node.js进程之间的通信

javascript - websockets ws.on 和 ws.onmessage 之间的区别

node.js - Meteor:如何将本地环境与生产环境分开?

node.js - 在 Express 路由文件中创建用户时出错

javascript - 使用 WebPack,我如何创建准备好使用 "split" bundle ,其中一个依赖于另一个?

mongodb - 没有重复的 Mongoose 帖子

node.js - Mongoose 更新数据信息,如何防止覆盖