【问题标题】:Mongoose how to update multiple subdocuments in different documents in one call - MERN stackMongoose如何一次调用更新不同文档中的多个子文档-MERN堆栈
【发布时间】:2019-08-03 20:35:36
【问题描述】:

我想通过 mongoose 进行 API 调用,以将一批选定的 Players(下图)cards 子文档的日期字段更新为当前日期。

播放器架构:

const playerSchema = new Schema({
  name: String,
  cards: [{
    date: { type: Date, required: true },
    note: String
  }],
});

我创建了一个复选框,用户可以在其中选择多个 Players(以及从他们的 cards 数组中选择一个特定的“卡片”子文档)并将所有选定 @987654326 的特定卡片的日期更改为相同@。在反应中,我在正文中将相应的 ObjectId 分批在一起,并将选定的玩家/卡片组合发送到如下所示的对象数组中(其中数字表示相同的分组玩家和卡片子文档 ObjectId):

我要发送到服务器的数组(可通过 req.body.cards 访问):

[ {cardId: card1._id, playerId: player1._id},
  {cardId: card2._id, playerId: player2._id},
  {cardId: card3._id, playerId: player3._id} ]

在我的 Node/Express 服务器 put 路由中,我将如何更新所有这些玩家和他们的特定卡片并异步给他们相同的日期 (Date.now())?换句话说,我将如何正确迭代所有不同的 playerId 和它们各自的 cardId(最好没有任何外部库)?

以下是我在常规放置路径中为单个玩家更新单张卡片以编辑 cards 子文档的方法:

Player.findById(playerId)
  .then(player => {
    const card = player.cards.id(cardId);
    card.date = Date.now();

    player.save(
      (err, updatedCard) =>
        err
          ? console.log("Error in update card: " + err)
          : res.send(updatedCard)
    );
  })
  .catch(err => res.status(404).json({ success: false }));

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我认为这应该可行。

    可以使用此查询更新单人游戏:-

    Player.findOneAndUpdate(
      { _id: playerId, "cards._id": cardId },
      { $set: { "cards.$.date": Date.now() } }
    );
    

    可以使用此查询更新多个玩家

    Player.update(
      { $or: [{ _id: player1Id, "cards._id": card1Id }, { _id: player2Id, "cards._id": card2Id }, { _id: player3Id, "cards._id": card3Id }] },
      { $set: { "cards.$.date": Date.now() } },
      { multi: true }
    );
    

    位置运算符 $ 将负责使用给定的卡片 ID 更新数组中的正确卡片。

    【讨论】:

    • thanks for this, very helpful, but when selecting more than one player for the multiple player update, I get MongoError: The positional operator did not find the match needed from the query. Also, we have to use Player.updateMany since update is deprecated.
    • 没关系,我将代码重新配置为仅发送子文档卡 ID,并将该数组与 { "cards._id": cards} 查询一起使用,这样就可以正常工作了
    猜你喜欢
    • 2020-04-20
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2015-07-12
    • 2019-10-05
    • 2012-10-27
    相关资源
    最近更新 更多