Skip to content

Conversation

futurliberta
Copy link
Contributor

Summary

I had a bug when deleting an entry from a populated Map.

Examples

import mongoose, { Schema } from 'mongoose';
import connectToDatabase from '@/server/libs/database/mongoose';

await connectToDatabase();

const playerSchema = new mongoose.Schema({
  name: String,
});

const PlayerModel = mongoose.model('PlayerTest', playerSchema);

const characterSchema = new mongoose.Schema({
  name: String,
  items: [{
    type: Schema.Types.ObjectId,
    ref: 'ItemTest',
  }],
});

const CharacterModel = mongoose.model('CharacterTest', characterSchema);

const itemSchema = new mongoose.Schema({
  name: String,
});

const ItemModel = mongoose.model('ItemTest', itemSchema);

const gameSchema = new mongoose.Schema({
  characters: {
    type: Map,
    of: {
      type: Schema.Types.ObjectId,
      ref: 'CharacterTest',
    },
    required: true,
  },
});

const GameModel = mongoose.model('GameTest', gameSchema);

const playerTest = await PlayerModel.create({ name: 'Player 1' });
const itemTest = await ItemModel.create({ name: 'Item 1' });
const characterTest = await CharacterModel.create({
  name: 'Character 1',
  items: [itemTest],
});

const gameTest = await GameModel.create({
  characters: {
    [playerTest.id]: characterTest,
  },
});

await gameTest.populate('characters');

console.log(gameTest.characters);

try {
  gameTest.characters.delete(playerTest.id); // <-- This will throw an error
  console.log('Deleted character from game');
} catch (err) {
  console.error(err); // TypeError: Cannot read properties of undefined (reading '$__')
}

lib/types/map.js Outdated
return v;
});
} else {
} else if (value) { // Fix when using delete method because the value is undefined
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is probably a better fix to do because of the value is undefined, we can probably skip a lot of checks

@vkarpov15 vkarpov15 added this to the 8.4.2 milestone Jun 10, 2024
@vkarpov15 vkarpov15 merged commit 7bc5395 into Automattic:master Jun 10, 2024
@vkarpov15
Copy link
Collaborator

Thanks 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants