In the schema, I have an object defender.placements.cruisers: []
i try to insert obj to it but it insert only status, direction, size
but empty grids
then i try to update again it remove the old data (status, direction, size)
and insert new data
//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);
below, the code that i try to push data to array in
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);
}
});
it works
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);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.