Skip to content

Conversation

@Himanshu197200
Copy link


Fix: Prevent Parent–Child Projection Collisions in Mongoose (#12798 )

Overview

This pull request fixes an issue where Mongoose generates invalid MongoDB projections when both a parent path and its nested child path are excluded. This occurs when combining:

  • Schema-level select: false fields
  • User-level .select('-parent') projections

MongoDB does not allow excluding both a parent and its child paths at the same time, resulting in a Path collision error.


The Problem

Given the following schema:

const BarSchema = new Schema({
  name: String,
  subd: {
    raw: { type: String, select: false },
    clean: String
  }
});

Running this query:

Bar.find().select('-subd');

Currently results in this projection:

{ 
  subd: 0,
  'subd.raw': 0   
}

MongoDB error:

Path collision: Cannot project both 'subd' and 'subd.raw'

The Fix

This PR ensures that nested child exclusions are removed automatically when the parent path is already excluded.

Correct behavior after fix:

{
  subd: 0
}

A new helper — removeConflictingProjections() — cleans up the projection before it is returned and forwarded to MongoDB.


Implementation Details

  • Updated parseProjection.js

  • Added removeConflictingProjections():

    • Detects excluded parent paths
    • Removes child-level exclusions that would cause collisions
  • Ensures compatibility with:

    • Schema-level select: false
    • Query-level .select() usage
    • Existing projection logic

Tests Added

A new test validates that:

  • Excluding a parent path removes nested exclusions
  • Schema-level defaults do not conflict with user projections
  • No MongoDB path collision occurs
  • All existing projection behavior remains unchanged

@Himanshu197200
Copy link
Author

@vkarpov15 Plz review this PR

@Himanshu197200
Copy link
Author

@vkarpov15 I made the changes according to the error , please review it.

@Himanshu197200
Copy link
Author

Hi @vkarpov15
I’ve made all the requested changes and updated the PR accordingly.
When you get a moment, could you please take another look and let me know if anything else is needed from my side?
Thanks for your time and guidance!

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