Uploaded image for project: 'MongoDB Shell'
  1. MongoDB Shell
  2. MONGOSH-1620

mongosh script db reference lost in js function

    • Type: Icon: Bug Bug
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • No version
    • Affects Version/s: None
    • Component/s: None
    • Labels:
      None
    • Environment:
      OS: archlinux 6.5.7-arch1-1
      node.js / npm versions: v20.7.0/10.1.0 (nvm)
      Additional info: mongosh 1.8.2
    • Not Needed

      Problem Statement/Rationale

      Writing mongosh script, which should execute qeuries for most of collections in my db, some aggregations need to be re-used, so put them into function, but when script executed and function called can see error <unknown>.collection is not a function. Converting function to arrow function does not help. Passing db as function argument make error db.collection is not a function.

      Please be sure to attach relevant logs with any sensitive data redacted.

      TypeError: <unknown>.collection is not a function
      TypeError: db.collection is not a function

      Steps to Reproduce

      ```js
      function getIds (collectionName, workspaceId, outputObjectIds = false) {
        const [result] = db
          .collection(collectionName)
          .aggregate([
            {
              $match:

      {           space_id: String(workspaceId),         }

      ,
            },
            {
              $group: {
                _id: null,
                ids: {
                  $push: outputObjectIds
                    ? '$_id'
                    :

      {                   $toString: '$_id',                 }

      ,
                },
              },
            },
          ])
          .toArray()

        return result?.ids ?? []
      }

      getIds('projects', someObjectId)
      ```

       

      Expected Results

      Aggregation inside function executed successfully as it happens in top level, and result returned

      Actual Results

      TypeError: <unknown>.collection is not a function
      TypeError: db.collection is not a function

       

      Also would like to ask, async/await seems not to be working, my guess is mongosh using something like fibers library (at least pretty similar to how meteor JS framework make async functions executed writter as sync code). Is there way to make my custom function same as mongodb related async commands written sync but actually executed async?

            Assignee:
            Unassigned Unassigned
            Reporter:
            ivan.c@taskworld.com Ivan Cherviakov
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: