【问题标题】:Model.update with Mongoose and $push overwrites the whole arrayModel.update 与 Mongoose 和 $push 覆盖整个数组
【发布时间】:2017-02-16 16:57:39
【问题描述】:

我在 MongoDB 中有一个非常简单的数据库,其中一部分包含在用户和游戏中。像这样的:

const GameSchema = new Schema({
  mode: Number
});

const UserSchema = new Schema({
  username: String,
  games: [{
    type: Schema.Types.ObjectId,
    ref: 'game'
  }]
});

所以现在当我创建游戏时,我还想更新游戏中的用户,添加 _id。例如,如果我创建了一个 _id 为 778 的游戏,而该游戏由 _id 为 111 和 222 的用户玩,那么这些用户的游戏属性将更新为添加 778。

在给定的时间内,同一个用户可能正在玩不同的游戏,因此用户游戏会不断发展,游戏:[778] => [778,889] => [778,889,901] 等等...

为此,我正在使用 Mongoose 中间件。

GameSchema.post('save', function(doc, next) {
  const User = mongoose.model('user');

  Game.findById(doc._id)
    .populate('players')
    .then(game => {
      let userIds = // retrieve the ids of the users playing the game

      if (userIds.length) {
        User.update(
            { _id: { $in: userIds } },
            { $push: { games: this._id } },
            { safe: true, multi: true }
          )
          .then((data) => {
            console.log('updated users', data);
            // here it says that both users were updated
            next();
          });
      } else {
        next();
      }
    });
});

问题是,游戏可以有 2 名玩家或 1 名玩家,在最后一种情况下,这很好用,但是当有 2 名用户要更新时,它不会更新游戏来添加新值,它基本上会覆盖整个数组,所以它是 [778] => [889] => [901]。

谁能帮助我或给我一个提示,我可以检查什么以了解发生了什么?

谢谢!

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    我才意识到发生了什么,这是我的错误。

    这已在数据库中正确更新,但由于 User.update 在中间件中,我没有返回更新的记录,因此我的 Web 应用程序中的对象没有更新。

    因此,当为双打创建新游戏时,我编辑了用户以添加一些控制信息,因此覆盖了游戏值。

    为这个问题道歉,愚蠢的错误。

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 1970-01-01
      • 2016-11-27
      • 2022-01-23
      • 1970-01-01
      • 2018-12-21
      • 2016-12-15
      • 1970-01-01
      • 2017-04-16
      相关资源
      最近更新 更多