0

I am trying to use mongoose to connect to a mongodb atlas cluster. When I run my app, I get the following error, after a long string of garbage output.

/path/node_modules/mongodb/lib/collection.js:74
            pkFactory: db.options?.pkFactory ?? utils_1.DEFAULT_PK_FACTORY,
                                  ^

SyntaxError: Invalid or unexpected token
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)

I've found the root cause to be: import mongoose from 'mongoose'. My code runs without it, but once I import I get this error. I don't even use mongoose anywhere else in the code yet.

I came across this post which covers the same question, but the only working solution is to downgrade mongoose to version 6.7.3.

I determined the change from mongoose 6.x to 7.x breaks my code. Furthermore, I think the actual break is from mongodb 4.x to 5.x. I looked into the notes for that change but I'm not sure how I could be importing it wrong. My node version is 16.17.0, npm version 8.15.0, and the mongodb version that gets installed is 5.6.0. My text encoding is utf-8.

1 Answers1

0

I think I have cracked it! My start script was node -r esm app.js, which is supposed to allow local runs for ECMAScript modules. There seems to be some compatibility issue with this for later versions of mongodb.

To solve:

First, remove the -r esm from your start command. Next, either:

  1. Change your .js extensions to .mjs (difference explained here)
  2. Add "type": "module" to your package.json

Both should have the same effect.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31