Mongo-如果子文档数组中的对象具有值,则添加字段

详细信息

我开发具有表达能力的调查应用程序,并为获取一些数据而苦恼。

情况:

  • 您可以通过“获取/调查”获得所有调查。如果用户对调查进行了投票,则每个调查文档都必须包含hasVoted:mongoose.BooloptionsVote: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”子文档,则如何添加字段votesuser===req.user.id


我相信您有这个主意,因此,如果您有一个如何更改架构以实现所需结果的主意,我会开放的!


示例:

  1. 数据:
[{
 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}
}]
  1. 路由处理程序:

req.user.id='userId1'处,然后进行 所需 查询。

  1. 结果
[{ // Voted for this survey
 id:"surveyId1
 question:"Question","1":0},hasVoted:true,{ // No voted for this survey
 id:"surveyId2
 question:"Question",votesCount:1,}]
fangmuxin1 回答:Mongo-如果子文档数组中的对象具有值,则添加字段

  1. 在MongoDB中,您可以按以下方式搜索子文档
hasVoted
  

因此,当您只能在用户投票的地方获得结果时,您真的需要optionsVote字段吗?

  1. 要具有optionsVote字段,首先我希望将{option: "a",count:1}的架构作为optionsVote。您可以选择以下任何一种方法。

    A。通过在您POST /survey/vote时增加投票选项的数量来设法在更新时更新optionsVote字段。

    B。另一种方法是在votes时根据GET /survey个条目计算//Mongodb query to get optionsVote:{option: "a",count:1} from votes: { user:"x",option:"a"} db.survey.aggregate([ { $unwind: "$votes" },{ $group: { "_id": { "id": "_id","option": "$votes.option" },optionCount: { $sum: 1 } } },{ $group: { "_id": "$_id.id" },optionsVote: { $push : { option: "$_id.option",count: "$optionCount" } },votes: { $push : '$votes'} } ]) //WARNING: I haven't tested this query,this is just to show the approach -> group based on votes.option and count all votes for that option for each document and then create optionsVote field by pushing all option with their count using $push into the field `optionsVote` 。您可以通过汇总

{{1}}

我推荐方法A,因为我认为POST操作将比GET操作少得多。而且它更容易实现。话虽如此,将查询保持在B位置会很方便,这将有助于您进行健全性检查。

本文链接:https://www.f2er.com/3163587.html

大家都在问