无法从 MongoDB Atlas Trigger 中的 collection 读取数据

Cant read data from collection in MongoDB Atlas Trigger

MongoDB 的新手,非常新的 Atlas。我正在尝试设置一个触发器,以便它从名为 Config 的 collection 中读取所有数据。这是我的尝试:

exports = function(changeEvent) {
  const mongodb = context.services.get("Cluster0");
  const db = mongodb.db("TestDB");
  var collection = db.collection("Config");
  config_docs = collection.find().toArray(); 
  console.log(JSON.stringify(config_docs));
}

该函数是名为 Triggers_RealmApp 的自动创建领域应用程序的一部分,该应用程序将 Cluster0 作为命名链接数据源。当我进入 Cluster0 中的 Collections 时,TestDB.Config 是 collections 之一。

一些注意事项:


图片: Collection: 关联数据源:

连接必须是到主副本集的连接,并且用户登录凭据是管理员级别的用户(需要有集群管理员的权限)

我最终直接用 MongoDB 处理了它,.find() 是异步的,我处理不当。以下是马口的直接回复:


据我了解,您没有从上面发布的查询中获得预期的结果。我知道当您刚开始使用一项新技术却无法正常工作时可能会感到困惑!

问题是 collection.find() 函数是一个异步函数。这意味着它发出请求但在继续之前不等待回复。相反,它 return 是一个 Promise,它是一个描述操作当前状态的对象。由于 Promise 实际上不是数组,因此您的语句 collection.find().toArray() 是 returning 一个空对象。您将这个空对象写入 console.log 并结束您的函数,甚至可能在使用您的数据进行异步调用之前 returns。

有几种方法可以解决这个问题。第一种是使您的函数成为异步函数,并使用 await 运算符告诉您的函数在继续之前等待 collection.find() 函数到 return。

exports = async function(changeEvent) {
  const mongodb = context.services.get("Cluster0");
  const db = mongodb.db("TestDB");
  var collection = db.collection("Config");
  config_docs = await collection.find().toArray(); 
  console.log(JSON.stringify(config_docs));

};

注意第一行的 async 关键字和倒数第二行的 await 关键字。

第二种方法是使用.then函数处理结果return:

exports = function(changeEvent) {
  const mongodb = context.services.get("Cluster0");
  const db = mongodb.db("TestDB");
  var collection = db.collection("Config");
  collection.find().toArray().then(config_docs => {
    console.log(JSON.stringify(config_docs));
  });
};