Unable to include external module in mongosh script

Hello,

I’m trying to run a script from a script.js in which I use require() to import additional logic from another js script. Example of the issue I’m running into:

in script.js I have the following:

const { updateFunc } = require("update.js"); const payload = {}; let updateResult = updateFunc()

in updateFunc I do the following:

const collection = db.users

const users = collection.find({}).toArray()

users.forEach(......)

This would give me the following errors:

TypeError: collection.find(...).toArray is not a function

or 

TypeError: users.forEach is not a function

If the script is written directly in script.js it works flawlessly. Could someone please help me understand what I’m doing wrong here? My understanding is that I could achieve what I’m trying to do with require(), but it doesn’t seem to work.

Hello @Karim_Abdelaziz, thank you for your question!

https://www.mongodb.com/docs/mongodb-shell/write-scripts/require-load-differences/ might be a helpful page for you to take a look at.

In particular, when using require(), you will be able to access Node.js APIs and other Node.js scripts, but not mongosh APIs like db or be able to use .find() and .toArray() like you normally would.

In this case, you probably just want to use load() instead of require(). load() lets you consume scripts that behave exactly as if they had been written for mongosh in the first place.

(Note that load() doesn’t work like require() in that it doesn’t return a value; you would just write a function as function updateFunc() { ... } without adding it to an exports object, and the function would just be available under that name in mongosh afterwards without needing to explicitly specify that it comes from require("...")).

I hope this helps!

1 Like