【发布时间】:2018-12-26 11:57:05
【问题描述】:
我有一个模式“问题”,其中包含十几个问题,我可以添加和删除这些问题,我需要将此集合反映在其他集合的字段中 - 带有一个附加字段的“用户”(嵌套在选项)。
问题架构:
var QuestionScema = new mongoose.Schema({
key: { type: String, required: true },
label: { type: String, required: true },
name: { type: String, required: true },
page: { type: String, required: true },
type: { type: String, required: true },
options: [{
key: {type: String, required: true},
value: {type: String, required: true}
}],
});
用户架构:
var UserSchema = new mongoose.Schema({
Name: { type: String, required: true },
Email: { type: String, required: true, unique: true },
Password: { type: String, required: true },
//this is where I need to reflect a Questions collection on each user,
//so that it will look something like this//
Questions: [{
key: {type: String, required: true},
//here can be all other fields from Questions collection, that is not a problem
options: [{
key: {type: String, reuired: true},
value: {type: String, reuired: true},
counter: {type: Number, default: 0} //this is the additional field
}]
}],
//
Notifications: [{
Title: { type: String },
Data: { type: String },
Created: { type: Date, default: Date.now }
}]
});
我不知道该怎么做。 我有另一个用户集合,比如 User2,它将回答来自 Questions 集合的这些问题,我需要跟踪用户模式(不是 User2,我只是保存问题和答案),了解为该问题选择了多少次选项。
Questiuons 条目可能如下所示:
{
key: Haveyouseenthismovie,
label: Have you seen this movie?,
name: Have you seen this movie?,
page: 1,
type: dropdown,
options: [{
key: yes,
value: yes
}, {
key: no,
value: no
}]
}
我希望它像那样工作(反映每个用户的字段中的集合)所以我不必检查该问题是否在用户集合中,如果没有添加,如果是,是否有我需要的选项如果不是增量,如果不是添加该选项(用户从问题架构中该问题的选项中选择)并增量。这看起来很糟糕。所以我认为如果该字段反映一个集合会更好,我将在我需要的问题上增加我需要的选项。 请帮我解决这个问题,我在 mongo 中没有足够的练习,所以我有时会很挣扎:)
【问题讨论】:
-
你的问题不是很清楚。据我了解,您需要维护一个集合列表、一个用户列表和另一个您将为每个用户维护的列表,他们回答了多少问题?这是正确的吗?这里计数器的目的是什么?你能解释一下你的确切问题陈述吗?
-
我有三个集合:问题、用户、用户2。 Questions 是我存储问题(和问题的答案选项)供 User2 回答的集合,在 User2 上我存储了一个条目列表,例如 {Q: 'have you senn a movie', A: 'yes' } 但 User2 是出了问题,我需要跟踪用户(而不是用户 2)用户 2 回答问题的每个选项的次数。所以它会像 {name: Have you seen this movie?: {yes: 1, no: 0} or name: Have you seen this movie?: [{yes: 1}, {no: 0}]。跨度>
-
为此,我认为我需要在 User 上反映 Questions 集合,因此我可以在 User2 回答该选项时增加我需要的选项。希望对你有帮助:)
-
我需要一个模式,以便每个用户都可以在上面找到所有问题和选项,因此我可以在需要时增加选项。或其他如果你有线索:)
-
您不能将问题和用户保存在一个集合中吗?您可以维护嵌入式文档。
标签: node.js mongodb mongoose database-design schema