【发布时间】:2020-03-01 05:45:33
【问题描述】:
详情
我使用 express 开发调查应用程序,但在获取一些数据方面遇到了困难。
案例:
- 您可以通过“GET /surveys”获取所有调查。如果用户投票支持调查,则每个调查文档都必须包含
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,
required: true,
}]
},
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,
}]
},
})
目标:
所以问题的目标是如果votes数组中有“投票”子文档user===req.user.id,如何添加字段hasVoted和optionsVote?
我相信你明白了,所以如果你知道如何更改架构以达到预期的结果,我愿意!
示例:
- 数据:
[{
id:"surveyId1
question:"Question",
options:["op1","op2"],
votes:[{user:"userId1", option:0}]
votesCount:1,
optionsVote:{"0":1,"1":0}
},{
id:"surveyId2
question:"Question",
options:["op1","op2"],
votes:[{user:"userId2", option:0}]
votesCount:1,
optionsVote:{"0":1,"1":0}
}]
- 路由处理程序:
Where req.user.id='userId1' 然后进行 desired 查询。
- 结果
[{ // Voted for this survey
id:"surveyId1
question:"Question",
options:["op1","op2"],
votes:[{user:"userId1", option:0}]
votesCount:1,
optionsVote:{"0":1,"1":0},
hasVoted:true,
},{ // No voted for this survey
id:"surveyId2
question:"Question",
options:["op1","op2"],
votesCount:1,
}]
【问题讨论】:
标签: database mongodb mongoose mongodb-query aggregation-framework