Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix problem when deleting an entry on a populated Map #14654

Merged
merged 2 commits into from
Jun 10, 2024

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
@@ -119,7 +119,7 @@ class MongooseMap extends Map {
v.$__.wasPopulated = { value: v._id };
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
23 checks passed
@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