Stitch Function returns Null value

I’m using MongodB Stitch functions to find one document by title on the sample_mflix.movies collection:

exports = function(arg){
  let collection = context.services.get("mongodb-atlas").db("sample_mflix").collection("movies");
  let doc = collection.findOne({"title": arg});
  return {doc};
};

When I run this in Node.js, I get {doc: null}. Here’s my Node.js code:

const {
    Stitch,
    AnonymousCredential
} = require('mongodb-stitch-server-sdk');

Stitch.initializeDefaultAppClient('mflix-dskle');
/*client.auth.loginWithCredential(new AnonymousCredential()).then(user => {
    console.log(user);
    client.close();
}).catch(err => {
    console.log(err);
    client.close();
});*/

const client = Stitch.defaultAppClient;
console.log("logging in anonymously");
 client.auth.loginWithCredential(new AnonymousCredential()).then(user => {
    console.log(`logged in anonymously as user ${user.id}`)
});
client.callFunction("getMovies", ["Adventures in Babysitting"]).then(result => {
    console.log(result);
});

Is this an issue with authentication? I’m using application authentication.

findOne is an async function. You either can “await” the result or you can use .findOne(…).then(doc => { … }).

try the following:

exports = async function(arg){ let collection = context.services.get("mongodb-atlas").db("sample_mflix").collection("movies"); let doc = await collection.findOne({"title": arg}); return {doc}; };

Thanks. I also noticed that when I use Anonymous Authentication the function returns an empty array {doc: [ ]}, but when I switch to System authentication I get a response back. Why does this happen?

This usually means that you’ve set some rules on you collection that prevent the Anonymous user to read/modify the document. Check your collection rules. Make sure that “non-owners” can read documents from you collection.