How to connect to Mongo DB Stitch from Node JS server

It took me a long time to figure this out, and mongo’s documentation is shitty.

First, in the stitch dashboard, go to users, then providers, then enable API Keys and create an api key. Save the key, put it in your javascript code.

Next you want to go back to the Stitch dashboard, go to rules, and create a new role with this pasted in the apply when:

{
"%%user.type": "server"
}

Give the document level permissions insert and delete. Then give all fields read and write access.

I was using Firebase cloud functions to map new data written in my firestore documents from a certain collection over to a collection in mongo db. (I do this because I need the insanely great query power of mongo, but I digress)

You need to install the stitch server sdk on your node server, do:

npm install mongodb-stitch-server-sdk
npm install mongodb-stitch-core-services-mongodb-remote

(or specifically choose which modules — more info here https://s3.amazonaws.com/stitch-sdks/js-server/docs/4/index.html)

Then you want to add this boilerplate to the top of your script:

const {
Stitch,
ServerApiKeyCredential,
RemoteMongoClient,
} = require('mongodb-stitch-server-sdk');
const{
RemoteUpdateOptions
} = require("mongodb-stitch-core-services-mongodb-remote")
const stitchClient = Stitch.initializeDefaultAppClient('your app id');
const mongoClient = stitchClient.getServiceClient(RemoteMongoClient.factory, "mongodb-atlas")
const mongoAPIKey = "your api key that you created in the stitch dashboard"

Now you can login and start calling mongo methods, which are well documented on their official server sdk docs, for example:

 stitchClient.auth.loginWithCredential(credential).then(credential => {
return mongoClient.db("YourDatabase").collection("users").updateOne({firebaseUserId: "userIdTest"}, {{firebaseUserId: "userIdTest", testField: 69420}, {upsert: true})
})