0

我创建了一个 AWS 账户并希望将 MongoDB Atlas 与 AWS Lambda 一起使用。我下载的唯一依赖项是本地的 mongodb。

npm install mongodb

从 mongoDB Atlas 为 Nodejs 提供的基于驱动程序的连接字符串是

var uri = "mongodb+srv://kay:myRealPassword@cluster0.mongodb.net/test";
MongoClient.connect(uri, function(err, client) {
   const collection = client.db("test").collection("devices");
   // perform actions on the collection object
   client.close();
});

我认为连接成功,因为err参数为NULL。

但我不知道如何创建集合、如何查找结果、如何插入文档。

我试过这段代码

module.exports.hello = (event, context, callback) => {

var MongoClient = require('mongodb').MongoClient;

var uri = "mongodb+srv://kay:myRealPassword@cluster0.mongodb.net/test";
MongoClient.connect(uri, function(err, client) {
   const collection = client.db("test").collection("devices");
   collection.insert( { "msg" : "My First Document" } );
   var results = client.db("test").collection("devices").find();
   console.log(results);
   client.close();
   callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
});

};

但它返回(在 Windows 控制台中)一个 JSON 格式的巨大对象,它就像一个配置数据(不是查询结果)

在此处输入图像描述

我正在本地执行此代码

sls invoke local --function hello
4

1 回答 1

0

大致思路是检查连接、插入等是否有错误。看看这个错误检查:

if (error) return 1;

有更复杂的方法,但对于您的情况,这应该可以完成工作。

这是它如何显示您的脚本的示例:

MongoClient.connect(uri, (error, client) => {
  if (error) return 1;    // Checking the connection
  console.log('Connection Successful');
  var db = client.db('mydb');        // Your DB

  let newDocument = { "msg" : "My First Document" };    // Your document

  db.collection('mycollection').insert(newDocument, (error, results) => {   // Your collection
    if (error) return 1;   // Checking the insert
    console.log('Insert Successful');
  })

  db.collection('mycollection')
    .find({})
    .toArray((error, accounts) => {
      if (error) return 1;   // Checking the find
      console.log('Find Successful');
      console.log(accounts);
      return 0;
  })

})

你应该有这样的输出:

Connection Successful
Insert Successful
Find Successful
[ { _id: 5a857dd2c940040d85cbe5f2, msg: 'My First Document' } ]

如果您的输出不是这样,那么丢失的日志将指向您出错的地方。

于 2018-02-15T12:53:23.570 回答