Skip to content

Commit

Permalink
Handle aggregate for discriminators
Browse files Browse the repository at this point in the history
  • Loading branch information
davellx committed Jun 12, 2023
1 parent 842c8f2 commit 2e8fd0d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
12 changes: 8 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,16 @@ module.exports = function (schema, options) {

if (finalList.indexOf('aggregate') > -1) {
schema.pre('aggregate', function() {
var firsMatchStr = JSON.stringify(this.pipeline()[0]);
var firstMatch = this.pipeline()[0];

if ( firsMatchStr !== '{"$match":{"deleted":{"$ne":false}}}' ) {
if (firsMatchStr === '{"$match":{"showAllDocuments":"true"}}') {
if(firstMatch.$match?.deleted?.$ne !== false){
if(firstMatch.$match?.showAllDocuments === 'true'){
var {showAllDocuments, ...replacement} = firstMatch.$match;
this.pipeline().shift();
} else {
if(Object.keys(replacement).length > 0){
this.pipeline().unshift({ $match: replacement });
}
}else{
this.pipeline().unshift({ $match: { deleted: { '$ne': true } } });
}
}
Expand Down
23 changes: 22 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1653,11 +1653,13 @@ describe("check usage of $ne operator", function () {
});

describe("aggregate methods: { overrideMethods: ['aggregate'] }", function () {
var TestSchema = new Schema({ name: String }, { collection: 'mongoose_delete_test_aggregate' });
var TestSchema = new Schema({ name: String }, { collection: 'mongoose_delete_test_aggregate', discriminatorKey:'kind' });
TestSchema.plugin(mongoose_delete, { overrideMethods: ['aggregate'] });

var TestModel = mongoose.model('Test5_Aggregate', TestSchema);

var DiscriminatorTestModel = TestModel.discriminator('DiscriminatorTest',new Schema({ age: Number }))

beforeEach(async function () {
await TestModel.create(
[
Expand Down Expand Up @@ -1743,6 +1745,25 @@ describe("aggregate methods: { overrideMethods: ['aggregate'] }", function () {
should.not.exist(err);
}
});


it("aggregateWithDeleted([{$project : {name : 1, age :1} }]) -> should return deleted documents from discriminator (pipeline)", async function () {
try {
await DiscriminatorTestModel.create(
[
{ name: 'Lando Calrissian', age: 46, deleted: true },
{ name: 'Han Solo', age:44 },
{ name: 'Jabba Desilijic Tiure', age:617, deleted: true }
]);
var documents = await DiscriminatorTestModel
.aggregateWithDeleted([{$match:{age:{$gte:50}}}])
.project({ name : 1, age:1 });

documents.length.should.equal(1);
} catch (err) {
should.not.exist(err);
}
});
});

describe("mongoose_delete find method overridden with populate", function () {
Expand Down

0 comments on commit 2e8fd0d

Please sign in to comment.