How to connect to MongoDB Atlas from Google App Engine

Hello, I started learning how to use MongoDB and I am trying now to connect to my database from a Google App Engine instance (flexible). I’m using NodeJS v16 and MongoDB v5.1 driver. I took the most basic code from here , yet the connection fails with the error MongoServerSelectionError: connection <monitor> to closed at Timeout._onTimeout and type: 'ReplicaSetNoPrimary'. From what I’ve read it has something to do with the IP address being blocked?

I saw saw a solution to use VPC network peering, but I’m using an M0 cluster for now so it doesn’t let me. Do I have to use a paid subscription to be able to connect from App Engine to the database? or is there a way to do it with the free tier, at least for testing?

This is my code, the connection part taken from the link above. Am I missing something?

const { MongoClient } = require("mongodb");

const uri = "mongodb+srv://NBirarov:<password>";
const mongoDBclient = new MongoClient(uri);

async function writeNewUser(email, tokenid){  //Calling this function after user logs in with email
    try {
        const database = mongoDBclient.db('RPerception');
        const users = database.collection('Users');
        const user = {
            "email": email,
            "tokenID": tokenid
        await users.insertOne(user);
        console.log('Email saved');

Thank you for the help

  • Update: I went to Network Access and added “Allow Access From Anywhere” and it works with that. Of course it is not a good idea for a finished product, so if anyone has other solutions I would appreciate it.

Hello @Yoav_Banitt ,

Welcome to The MongoDB Community Forums! :wave:

As mentioned in your update, the issue was that your IP was not added in your IP Access List at MongoDB Atlas side. This is a security feature and Atlas only allows client connections to the database deployment from entries in the project’s IP access list.

A quick google search provides below result which might be helpful in figuring out Outbound IP addresses for App Engine services. I am not familiar with Google App Engine hence won’t be able to help regarding the configuration of outbound ip address from App Engine.

For more details regarding MongoDB Atlas IP Access Entries, please check