Navigation

Access MongoDB Remotely

Overview

You can query data stored in MongoDB directly from your client application code with the MongoDB query language by using MongoDB Realm’s RemoteMongoClient on a RealmUser object. MongoDB Realm provides data access rules for collections to securely retrieve results based on the logged-in user or the content of each document.

Prerequisites

Before you can remotely access MongoDB, you must:

Use the RemoteMongoClient to Query For Data In Your Collection

Note

The following code snippet requires that Anonymous Authentication is enabled in your MongoDB Realm App.

const Realm = require("realm");
const appId = "<appId>"; // Set Realm app ID here.

const appConfig = {
  id: appId,
  timeout: 1000,
};

async function run() {
  let user;
  try {
    const app = new Realm.App(appConfig);

    const credentials = Realm.Credentials.anonymous(); // create an anonymous credential
    user = await app.logIn(credentials);

    const mongo = user.remoteMongoClient("mongodb-atlas");
    const coll = mongo.db("exampleDB").collection("exampleCollection");

    item = await coll.findOne({});
    console.log(item);

  } finally {
    user.logOut();
  }
}
run().catch(console.dir);