Uploaded image for project: 'Node.js Driver'
  1. Node.js Driver
  2. NODE-3455

ProjectionOperators type is too narrow in Node.js driver

    • Type: Icon: Bug Bug
    • Resolution: Duplicate
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: None
    • Component/s: Native
    • 2
    • Not Needed

      What problem are you facing?

      ProjectionOperators's type definition ($slice specifically) seems to be too narrow. The following works (all unit and integration tests pass), but fails the type check on account of the string literal expression, sum expression, and that it's a three element array.

      Failing example:

      Unable to find source-code formatter for language: typescript. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      (await memes
          .find({ _id: meme_id })
          .project<{ likes: UserId[] }>({
            likes: {
              $slice: [
                '$likes',
                after ? { $sum: [{ $indexOfArray: ['$likes', after] }, 1] } : 0,
                getEnv().RESULTS_PER_PAGE
              ]
            }
          })
          .next()
      

      With TypeScript reporting the following errors:

      error TS2322: Type 'string' is not assignable to type 'number'.
      
      ==>               '$likes',
                        ~~~~~~~~
      
      src/backend/index.ts:336:15 - error TS2322: Type 'number | { $sum: (number | { $indexOfArray: (string | ObjectId)[]; })[]; }' is not assignable to type 'number'.
        Type '{ $sum: (number | { $indexOfArray: (string | ObjectId)[]; })[]; }' is not assignable to type 'number'.
      
      ==>               after ? { $sum: [{ $indexOfArray: ['$likes', after] }, 1] } : 0,
                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      
      src/backend/index.ts:337:15 - error TS2322: Type 'number' is not assignable to type 'undefined'.
      
      ==>               getEnv().RESULTS_PER_PAGE
      

      If instead I use the suggested [number, number] form (removing the '$likes' element), TypeScript is satisfied but I get the following runtime error:

      MongoServerError: First argument to $slice must be an array, but is of type: int
      

      What driver and relevant dependency versions are you using?

      • Node.js native driver mongodb@4.0.0
      • Using latest MongoDb 4.x
      • Previously used @types/mongodb

      Steps to reproduce?

      See above.

            Assignee:
            Unassigned Unassigned
            Reporter:
            git@ergodark.com Bernard Dickens
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: