如何在mongodb中使用meteor找到正确的数组并将数据推送到meteor.users自定义数组字段?

时间:2016-02-23 11:22:30

标签: mongodb meteor

如何找到正确的course_id并将“myclass2”推送到classes_id字段,这是一个数组?

我有这个,但它为类增加了一行

let data = Meteor.users.update({_id: Meteor.userId(), "classes.course_id": course_id}, {
   $push: {
        "classes": {
            "classes_id": [class_name]
        }
    }}
)

错误的更新:

{
  "_id": "RoFFcaAfXBeR2napZ",
  "emails": [
    {
      "address": "tong@gmail.com",
      "verified": false
    }
  ],
  "classes": [
      {
         "course_id": "svesvinfdsgrvnekuktndvsk",
         "classes_id": ["myclass1"]
      },
      {
         "course_id": "rgjjgdcrvnevghjcdvbbvddv",
         "classes_id": ["myclass1"]
      },
      {
         "classes_id": ["myclass2"]<----wrong update
      },
  ],
  "courses": [
    "qwmZdgQbrZ3rmHdN8"
  ]
}

添加前

{
  "_id": "RoFFcaAfXBeR2napZ",
  "emails": [
    {
      "address": "tong@gmail.com",
      "verified": false
    }
  ],
  "classes": [
      {
         "course_id": "svesvinfdsgrvnekuktndvsk",
         "classes_id": ["myclass1"]
      },
      {
         "course_id": "rgjjgdcrvnevghjcdvbbvddv",
         "classes_id": ["myclass1"]
      },
  ],
  "courses": [
    "qwmZdgQbrZ3rmHdN8"
  ]
}

我如何实现这一目标?如果我能找到course_id

,请将myclass2添加到classes_id
{
  "_id": "RoFFcaAfXBeR2napZ",
  "emails": [
    {
      "address": "tong@gmail.com",
      "verified": false
    }
  ],
  "classes": [
      {
         "course_id": "svesvinfdsgrvnekuktndvsk",
         "classes_id": ["myclass1", "myclass2"]<----correct
      },
     {
         "course_id": "rgjjgdcrvnevghjcdvbbvddv",
         "classes_id": ["myclass1"]
      },
  ],
  "courses": [
    "qwmZdgQbrZ3rmHdN8"
  ]
}

2 个答案:

答案 0 :(得分:2)

您可以使用positional $ operator

function addClassId(userId, courseId, classId) {
  c1.update({
    _id: userId,
    'classes.course_id': courseId
  }, {
    $push: {
      'classes.$.classes_id': classId
    }
  });
};  

它会从classes数组中获得第一个匹配项并将classId推送到其classes_id数组中。

答案 1 :(得分:0)

这个有效!

let data = Meteor.users.update({_id: Meteor.userId(), "classes.course_id": course_id}, {
     $push: {"classes.$.classes_id": class_name}
})