详细信息
我开发具有表达能力的调查应用程序,并为获取一些数据而苦恼。
情况:
- 您可以通过“获取/调查”获得所有调查。如果用户对调查进行了投票,则每个调查文档都必须包含
hasVoted:mongoose.Bool
和optionsVote:mongoose.Map
。 (SurveySchema在下面) - 您可以通过“ POST / surveys / vote”投票给调查
- 只有您投票,您才能查看任何调查的结果
new Schema({
question: {
type: mongoose.Schema.Types.String,required: true,},options: {
type: [{
type: mongoose.Schema.Types.String,}]
},optionsVote: {
type: mongoose.Schema.Types.Map,of: mongoose.Schema.Types.Number,votesCount: {
type: mongoose.Schema.Types.Number,votes: {
type: [{
user: {
type: mongoose.Schema.Types.ObjectId,ref: 'User',option: mongoose.Schema.Types.Number,})
目标:
所以问题的目标是,如果hasVoted
数组中有optionsVote
的“ Vote”子文档,则如何添加字段votes
和user===req.user.id
?
我相信您有这个主意,因此,如果您有一个如何更改架构以实现所需结果的主意,我会开放的!
示例:
- 数据:
[{
id:"surveyId1
question:"Question",options:["op1","op2"],votes:[{user:"userId1",option:0}]
votesCount:1,optionsVote:{"0":1,"1":0}
},{
id:"surveyId2
question:"Question",votes:[{user:"userId2","1":0}
}]
- 路由处理程序:
在req.user.id='userId1'
处,然后进行 所需 查询。
- 结果
[{ // Voted for this survey
id:"surveyId1
question:"Question","1":0},hasVoted:true,{ // No voted for this survey
id:"surveyId2
question:"Question",votesCount:1,}]