如何在 Meteor 方法中 运行 `$set` 和 `$pull`?

How to run a `$set` and `$pull` within a Meteor method?

我想通过名为 classroom.delete 的方法更新名为 SMUProfiles 的集合。我想从 SMUProfiles 内的 2 个位置拉出 classroom_id,即一个在 classrooms.owner 内,它有一个代码数组,另一个在数组 classrooms.students.[=21= 内]

我已经成功地设置了 $set 部分,现在尝试添加 $pull,但是 $pull 似乎没有用。

$set$pull可以这样吗?

/* Method for deleting Classroom */
'classroom.delete'(classroom_id) {
  if (!this.userId) {
    throw new Meteor.Error('not-authorised');
  }
  Classrooms.remove(classroom_id)
  let classids = Classrooms.find({ owner: this.userId }).fetch().map(function(classrooms){
    return classrooms._id })
  //console.log(classids);
  SMUProfiles.update({
      owner: this.userId,
    }, {
      $set: {
        'classrooms.owner': classids
      },
      $pull: {
        'classrooms.students': classroom_id
      }
    }
  )
}

您正在尝试在同一个更新的同一个字段上 $set$pull - 这两个操作冲突;所以不,你不能以这种方式使用这些运算符。

您可以轻松地将其分成两部分:

SMUProfiles.update(
  { owner: this.userId },
  { $set: { 'classrooms.owner': classids },
);
SMUProfiles.update(
  { owner: this.userId },
  { $pull: { 'classrooms.students': classroom_id },
);

参见例如this answer