'MongoDB atlas trigger getting error: TypeError: Cannot access member 'db' of undefined

I am a newbie trying MongoDB-atlas free tier. I have a cluster named - "mongoCluster. Under it, I have a database - "testdb" and under it, have a collection - "testcollection". This collection has documents. The inserts and read from my java app are working fine.

Now I am trying to create a new scheduled trigger in MongoDB atlas. But as I am running the following two lines, I am getting the following error. Same holds true for any other mongo query like delete, update and insert.

Code:

exports = function() {
  
    const collection=context.services.get("mongoCluster").db("testdb").collection("testcollection");
    collection.insertOne({"a": "b"});
   // const doc = collection.findOne();

};

Error:

> ran on Mon Nov 16 2020 18:52:52 GMT-0800 (Pacific Standard Time)
> took 272.591178ms
> error: 
TypeError: Cannot access member 'db' of undefined
> trace: 
TypeError: Cannot access member 'db' of undefined
    at exports (function.js:24:24)
    at apply (<native code>)
    at function_wrapper.js:3:1
    at <anonymous>:8:1

Looking at the error, either the service name is incorrect ("undefined error") OR I am missing some permissions on the service/database/collection ("anonymous:8:1 error").

I read somewhere in the MongoDB documentation, the service name = cluster name. Is there a way to see whats my service name? Have tried service name in lower case too, but no luck. Also tried same with fully qualified service name - "mongocluster.qeat9.mongodb.net", same error.

Or it is something else I am missing? Can someone please help here?

EDIT 1:

Adding a screenshot of the trigger function text which has the sample commented code. See the second line from the bottom which shows the syntax I have been using.

enter image description here

Thanks in Advance!



Solution 1:[1]

I linked an example of the page where you should be able to find your linked clusters ("Linked Data Sources" in the side-nav). Then you can use that service name in context.services.get("my-svc")...

enter image description here

Solution 2:[2]

In my case, I had to use the actual cluster name instead of the mongodb-atlas

Solution 3:[3]

First, make sure what trigger you want to use. refer docs: mongodb trigger-types

Then, you have to link the data source (click on the button) Link the data source image

After that, you have to use the cluster name instead of "mongodb-atlas" as said in the comments of a Scheduled Trigger See comments here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 haley
Solution 2 Anton Plebanovich
Solution 3 bhucho