deleteMany on a discriminator removes all documents in shared collection
I could be missing that this is expected behavior, but can't find anything in the documentation about this. remove has deprecation warnings so we are moving to deleteMany, however when using discriminators, the behavior is different. Using remove on a model, only those documents that match the model will be removed. When using deleteMany, all documents from the base model (shared in the collection by the discriminator) are deleted.
Here is what I did to test
const PeopleSchema = new mongoose.Schema({
job: {type: String},
name: {type: String}
}, {discriminatorKey: 'job'});
let People = mongoose.model('People', PeopleSchema);
const DesignerSchema = new mongoose.Schema({
badge: {type: String}
});
let Designer = People.discriminator('Designer', DesignerSchema);
const DeveloperSchema = new mongoose.Schema({
coffeeAmount: {type: Number}
});
let Developer = People.discriminator('Developer', DeveloperSchema);
let runTest = async function() {
await Designer.create([
{name: 'Bob', badge: '1234'},
{name: 'Jeff', badge: '1234'},
{name: 'Josh', badge: '1234'},
{name: 'Billy', badge: '1234'},
{name: 'Sam', badge: '1234'}
]);
await Developer.create([
{name: 'Ryan', coffeeAmount: 2},
{name: 'Rob', coffeeAmount: 2},
{name: 'Ben', coffeeAmount: 2}
]);
let startCount = await People.countDocuments({});
console.log(`there are ${startCount} in the db`);
// await Developer.remove();
await Developer.deleteMany();
let newCount = await People.countDocuments({});
console.log(`now there are ${newCount} in the db`);
}
runTest();
In the test, if I use remove there are 5 documents left. When I run with deleteMany there are 0 left.
I also don't see that remove is being deprecated here or here, but I do get logged warnings when using it, which is why the switch to deleteMany.
Thanks for reporting. This issue only happens if you do Developer.deleteMany(), Developer.deleteMany({}) works as expected. Fix will be in v5.8.5 :+1: