如何在lambda函数中使用nodejs将mongodb输出存储在变量中? [英] How to store mongodb output in variable using nodejs in lambda function?

查看:154
本文介绍了如何在lambda函数中使用nodejs将mongodb输出存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在lambda函数中,我有以下代码:

In a lambda function, I have the following code:

var user;

exports.handler = function uploadToS3(event, context, callback) {
  var name = event["username"];
  MongoClient.connect(uri, { useNewUrlParser: true }, (error, client) => {
    if (error) return 1; // Checking the connection
    db = client.db(databasename);
    db.collection("user_profile").findOne({ username: name }, function(
      err,
      result
    ) {
      if (err) throw err;
      user = result._id;
      console.log(user); // 1st console.log
    });
  });
  console.log(user); //2nd console.log
};

在上面的代码中,我已将user声明为全局变量.在第一个console.log中,它将显示该值,但在第二个console.log中,它将显示未定义.找到以下lambda函数的输出.

In the above code, I have declared user as a global variable. In 1st console.log it will display the value but in 2nd console.log it will undefined. find the below output of lambda function.

Function Logs:
2019-08-23T15:23:34.610Z    83141f62-f840-4e52-9440-35f3be7b0dc8     
5d5eaa9f921ed00001ee1c3f
2019-08-23T15:23:34.192Z    83141f62-f840-4e52-9440-35f3be7b0dc8     
undefined

在第二种情况下如何获取值?

How can I get a value in the second case?

推荐答案

问题不在于将mongodb输出存储到变量中,而是因为它是同步还是异步行为.设计上的Java脚本是同步的,但具有处理异步任务的能力.执行mongo查询的方法是异步的.阅读:Javascript调用findOne(),这将返回一个待定"的Promise,然后您的脚本继续调用console.log(user)-仍未定义.当来自MongoDB的请求返回时,javascript会解析promise并执行任何进一步的操作和/或回调.

The problem is not so much storing the mongodb output into a variable, as it is a synchronous vs asynchronous behavior. Javascript by design is synchronous, but has capability to handle asynchronous tasks. The method that performs the mongo query is asynchronous. Read: Javascript calls findOne(), this returns an 'pending' promise, then your script continues to call console.log(user) - which is still undefined. When the request from MongoDB comes back, javascript resolves the promise and executes any further actions and/or callbacks.

第二个console.log返回并在mongo客户端返回响应并为您的变量分配新值之前进行评估.如果查看响应的时间戳,则未定义的响应将在具有值的响应之前返回.看起来您正在使用猫鼬,它将返回一个Promise,您可以尝试将第二个调用放入.then或.done块中.例如:

The second console.log comes back and is evaluated BEFORE the mongo client returns a response and assigns a new value to your variable. If you look at the timestamp of the responses, the undefined one comes back before the one with the value. It looks like you are using mongoose, which should return a promise and you can try putting that second call inside a .then, or a .done block. e.g:

var user;

exports.handler = function uploadToS3(event, context, callback) {
  var name = event["username"];
  MongoClient.connect(uri, { useNewUrlParser: true }, (error, client) => {
    if (error) return 1; // Checking the connection
    db = client.db(databasename);
    db.collection("user_profile").findOne({ username: name }, function(
      err,
      result
    ) {
      if (err) throw err;
      user = result._id;
      console.log(user); // 1st console.log
    })
    .done(function(){
      console.log(user); //2nd console.log
    });
  });  
};

如果不使用猫鼬,请做出自己的承诺,或使用回调,或尝试使用猫鼬(它会摇晃!):)

If not using mongoose... make your own promise, or use a callback, or just try Mongoose (it rocks!) :)

*请注意,我将.done放在findOne()之后,但是我相信您也可以将.done()附加到.connect()上. (不要在上面引用我.您必须对其进行测试,看看该承诺何时会完全解决)

*note that I put the .done after the findOne(), but I believe you could attach a .done() to the .connect() as well. (Don't quote me on that. You would have to test it, see when that promise resolves exactly)

此外,我建议您以某种方式在lambda之外存储此值.对于每个lambda执行,您可能不会启动相同的容器.您可能会对此产生一些问题.

Additionally, I would suggest storing this value outside of your lambda somehow. You might not get the same container bootstrapped for each lambda execution. You could have some issues with this down the line.

退房:

  • AWS Lambda caching issues with Global Variables - https://medium.com/tensult/aws-lambda-function-issues-with-global-variables-eb5785d4b876
  • Improving Performance From Your Lambda Function From the Use of Global Variables - https://blog.ruanbekker.com/blog/2018/08/27/improving-performance-from-your-lambda-function-from-the-use-of-global-variables/
  • AWS Lambda best practices - https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html

这篇关于如何在lambda函数中使用nodejs将mongodb输出存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆