forked from Automattic/mongoose
/
lambda.pug
106 lines (79 loc) · 4.52 KB
/
lambda.pug
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
extends layout
block append style
link(rel="stylesheet" href="/docs/css/inlinecpc.css")
script(type="text/javascript" src="/docs/js/native.js")
block content
<a class="edit-docs-link" href="#{editLink}" target="_blank">
<img src="/docs/images/pencil.svg" />
</a>
h2 Using Mongoose With AWS Lambda
:markdown
<script>
_native.init("CK7DT53U",{
targetClass: 'native-inline'
});
</script>
<div class="native-inline">
<a href="#native_link#"><span class="sponsor">Sponsor</span> #native_company# — #native_desc#</a>
</div>
[AWS Lambda](https://aws.amazon.com/lambda/) is a popular service for running
arbitrary functions without managing individual servers. Using Mongoose in your
AWS Lambda functions is easy. Here's a sample function that connects to a
MongoDB instance and finds a single document:
```javascript
const mongoose = require('mongoose');
let conn = null;
const uri = 'YOUR CONNECTION STRING HERE';
exports.handler = async function(event, context) {
// Make sure to add this so you can re-use `conn` between function calls.
// See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
context.callbackWaitsForEmptyEventLoop = false;
// Because `conn` is in the global scope, Lambda may retain it between
// function calls thanks to `callbackWaitsForEmptyEventLoop`.
// This means your Lambda function doesn't have to go through the
// potentially expensive process of connecting to MongoDB every time.
if (conn == null) {
conn = mongoose.createConnection(uri, {
// Buffering means mongoose will queue up operations if it gets
// disconnected from MongoDB and send them when it reconnects.
// With serverless, better to fail fast if not connected.
bufferCommands: false, // Disable mongoose buffering
bufferMaxEntries: 0 // and MongoDB driver buffering
});
// `await`ing connection after assigning to the `conn` variable
// to avoid multiple function calls creating new connections
await conn;
conn.model('Test', new mongoose.Schema({ name: String }));
}
const M = conn.model('Test');
const doc = await M.findOne();
console.log(doc);
return doc;
};
```
To import this function into Lambda, go [the AWS Lambda console](https://console.aws.amazon.com/lambda)
and click "Create Function".
<a href="https://i.imgur.com/FlAD0vT.png"><img src="https://i.imgur.com/FlAD0vT.png"></a>
Create a function called "mongoose-test" with the below settings:
<a href="https://i.imgur.com/YOYJzeO.png"><img src="https://i.imgur.com/YOYJzeO.png"></a>
Copy the source code into a file called `lambda.js`. Then run `npm install mongoose co`.
Finally, run `zip -r mongoose-test.zip node_modules/ lambda.js` to create a
zip that you can upload to Lambda using the "Upload a Zip File" option under "Function code".
Make sure you also change the "Handler" input to `lambda.handler` to match the `lambda.js` file's `handler` function.
<a href="https://i.imgur.com/BXc9egq.png"><img src="https://i.imgur.com/BXc9egq.png"></a>
Next, click the "Save" button and then the "Test" button. The "Test" button will
ask you to create a new test event, just create one because your inputs don't matter
for this example. Then, hit "Test" again to actually run your function:
<a href="https://i.imgur.com/2UKtWYq.png"><img src="https://i.imgur.com/2UKtWYq.png"></a>
If your MongoDB database goes down in between function calls, you may
see the below error message:
```
cannot find account after reload: could not find config for <hostname>
```
Lambda's JavaScript framework recently added support for
async/await as long as you're using Node 8.x, so make sure you're not
using Node.js 6.x.
*Want to learn how to check whether your favorite JavaScript frameworks, like [Express](http://expressjs.com/) or [React](https://reactjs.org/), work with async/await? Spoiler alert: neither Express nor React support async/await. Chapter 4 of Mastering Async/Await explains the basic principles for determining whether a framework supports async/await. [Get your copy!](http://asyncawait.net/?utm_source=mongoosejs&utm_campaign=lambda)*
<a href="http://asyncawait.net/?utm_source=mongoosejs&utm_campaign=lambda" style="margin-left: 100px">
<img src="/docs/images/asyncawait.png" style="width: 650px" />
</a>