我有一个模式“问题”它有十几个问题,我可以添加和删除这些问题,我需要这个集合反映在其他集合的字段 - “用户”与一个额外的字段(嵌套在选项中)。
问题架构:
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将回答问题集合中的那些问题,我需要跟踪用户模式(不是User2,我只保存问题和答案)选择该问题的选项的次数。
问题条目可能如下所示:
{
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
}]
}
我想让它像那样工作(反映每个用户的字段中的集合)所以我不必检查该问题是否在User集合中,如果没有添加,如果是,是否有我需要的选项,如果它是比增量,如果不是添加该选项(该用户从问题模式中该选项中的选项中选择)并递增。这看起来像一个无赖。所以我认为如果该字段将反映一个集合会更好,我只会在我需要的问题上增加我需要的选项。请帮我搞清楚,我没有足够的mongo练习所以我有时候会挣扎:)
我认为没有办法像你希望的那样在另一个文档中反映一个集合。
据我了解,您可以使用以下选项:
请阅读数据建模概念并维护Mongo DB Page https://docs.mongodb.com/manual/applications/data-models-relationships/中文档之间的关系