Mongoose更新嵌套数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mongoose更新嵌套数组相关的知识,希望对你有一定的参考价值。

在架构中,我有一个对象defender.placements.cruisers: []我尝试插入obj到它但它只插入status, direction, size但空grids然后我尝试再次更新它删除旧数据(status, direction, size)并插入新数据

//My Model
import mongoose from 'mongoose';
const Schema = mongoose.Schema;

export const CoordinateSchema = new Schema({row: Number, col: Number});
export const ShipSchema = new Schema({
  grids: [CoordinateSchema],
  status: String,
  direction: String,
  size: Number
});
export const GameStateSchema = new Schema({
  gameState: {
    type: String,
    required: 'state status',
    default: 'joining'
  },
  attacker: {
    hitGrids: [CoordinateSchema],
    missGrids: [CoordinateSchema]
  },
  defender: {
    placements: {
      battleships: [ShipSchema],
      cruisers: [ShipSchema],
      destroyers: [ShipSchema],
      submarines: [ShipSchema]
    }
  },
  occupyGrids: [CoordinateSchema],
  adjacentGrids: [CoordinateSchema],
  size: {
    type: String,
    default: '10'
  }
});

export default mongoose.model('GameState', GameStateSchema);

下面,我尝试将数据推送到数组中的代码

await GameState.update({
      _id: testId
    },{
      $set: {
        'defender.placements': {
          [shipType]: {
            status: utils.shipStatus.float,
            direction: shipDirection,
            size: coordinates.length,
            $addToSet: {
              grids: coordinates
            }
          }
        }
      },
      $addToSet: {
        occupyGrids: coordinates,
        adjacentGrids: closeGrids
      }
    }, (err, gm) => {
      if (err) {
        return res.send(err);
      }
    });

这是我的结果,但我得到了enter image description here

答案

有用

const newPlacements = [{
      grids: [...coordinates],
      status: utils.shipStatus.float,
      direction: shipDirection,
      size: coordinates.length
    }];
const keyPlacements = `defender.placements.${shipType}`;
    await GameState.update({
      _id: testId
    },{
      $addToSet: {
        [keyPlacements]: newPlacements,
        occupyGrids: coordinates,
        adjacentGrids: closeGrids
      }
    }, (err, gm) => {
      if (err) {
        return res.send(err);
      }
    });

以上是关于Mongoose更新嵌套数组的主要内容,如果未能解决你的问题,请参考以下文章

Mongoose更新嵌套数组

Mongoose - 更新嵌套数组中的字段

Mongoose - 更新嵌套数组中的字段

Mongoose findOneAndUpdate:创建然后更新嵌套数组

Mongoose findOneAndUpdate:创建然后更新嵌套数组

如何在 mongodb/mongoose 的嵌套数组中检查是不是存在并更新对象?