Mongoose更新嵌套数组

问题描述 投票:1回答:1

在架构中,我有一个对象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

node.js mongodb mongoose
1个回答
0
投票

有用

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);
      }
    });
© www.soinside.com 2019 - 2024. All rights reserved.