0

I'm using MongoDB + Mongoose + Node.JS

App logic: We have a game similar to minesweeper. User selected cells in game field store in fields: Array, and bombs locations store in bombs: Array.

When user performing a request to select a cell in game, server must set fields[cell] = 1 // 1 means cell is selected. If the bomb in cell bombs[cell] === 1 // 1 means bomb in cell we need to make different update, like fields[cell] = 1; winning = 0. How to realize it in one query?

I tried to make a query, wich change only field[cell] = 1, but don't change winning = 0 if inside field detected bomb.



Code:

const selection = await db.Minesweeper.findOneAndUpdate({
    uid,
    winning: null,
}, {
    $set: { [`fields.${cell}`]: 1, },
    // I need to set winning = 0, if [bombs.${cell}] = 1
});

Game schema:

const MinesweeperSchema = new mongoose.Schema({
    uid: { type: Number, required: true },
    bet: { type: Number, required: true },
    winning: { type: Number, default: null },
    fields: { type: Array, default: new Array(5*5).fill(0) },
    bombs: { type: Array, required: true },
},
{ timestamps: true });



Well, again:

I need that logic: If selected cell contains a bomb, set field[cell_index] = 1; winning = 0, but if cell don't contains a bomb, set field[cell_index] = 1

put on hold as off-topic by mustaccio, Philᵀᴹ, Marcello Miorelli, John Eisbrener, LowlyDBA Nov 14 at 14:58

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

0

I believe you can use the aggregation pipeline for updates using the conditional operator.

For example, change your update object to be an array like this:

[
    { $addFields: 
        { "winning" : { $cond: { if: { $eq: [ "$fields.11", 1 ] }, then: 22, else: 33 } } } 
    } 
]

This specifies that if the element 11 of the fields array equals to 1, then set the winning field to 22, or else set winning to 33.

Not the answer you're looking for? Browse other questions tagged or ask your own question.