Skip to content

core-users: findUsers with usernames/emails throws MongoServerError "cannot nest $ under $in" #733

Description

@pozylon

Bug

buildFindSelector in packages/core-users/src/module/configureUsersModule.ts builds an invalid MongoDB query when usernames or emails are passed:

if (usernames?.length) {
  selector.username = {
    $in: usernames.map((u) => insensitiveTrimmedRegexOperator(u)),
  } as any;
}
if (emails?.length) {
  selector['emails.address'] = {
    $in: emails.map((e) => insensitiveTrimmedRegexOperator(e)),
  } as any;
}

insensitiveTrimmedRegexOperator (in @unchainedshop/mongodb) returns an operator document { $regex: RegExp }. MongoDB allows plain regex values inside $in, but not operator documents, so any findUsers({ usernames: [...] }) / findUsers({ emails: [...] }) call fails with:

MongoServerError: cannot nest $ under $in
  code: 2, codeName: 'BadValue'

Affects the released 4.8.22 — present on both the v4.8.x branch (configureUsersModule.ts L87–95) and master (L86–94). A patch on v4.8.x (→ 4.8.23) would be appreciated.

Repro

await modules.users.findUsers({ usernames: ['someuser'] });
// MongoServerError: cannot nest $ under $in

Suggested fix

Map to raw RegExp values instead of the { $regex } wrapper, e.g.:

$in: usernames.map((u) => insensitiveTrimmedRegexOperator(u).$regex)

or add a helper that returns the bare RegExp for use inside $in.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions