连接Mongoose和AWS Lambda函数



我想在netflix和Mongoose中使用lambda函数。基本上是在前端触发一个函数并更新DB。

const mongoose = require('mongoose')
let uri = 'mongodb+srv://...flashcard?retryWrites=true&w=majority'
let client = mongoose.connect(`${uri}`, {
useNewUrlParser: true
}
);
const clientPromise = client.connect()
exports.handler = async (event, context, callback) => {

context.callbackWaitsForEmptyEventLoop = false;

try {    

client = await clientPromise;
client.db('flashcards').createCollection('hello')
return {
statusCode: 200,
};
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }) 
};
}
}

这不起作用,返回

500 Internal Server Error Cannot read properties of undefined (reading 'connect')

但是,如果我在MongoClient中这样做,并且只更改第一部分,它就可以工作并更新DB。


const { MongoClient } = require('mongodb');

let uri = 'mongodb+srv://...flashcard?retryWrites=true&w=majority'
let client = new MongoClient(`${uri}`, {
useNewUrlParser: true
}
);

我怎么能用猫鼬来做呢?感谢阅读!

我从

中选取了工作示例
https://www.mongodb.com/docs/atlas/manage-connections-aws-lambda/

我是这样做的。我使用react.js并在netflix上部署了一个简单的网站来检查他们的无服务器功能是如何工作的。在这个例子中,我只是从表单发送电子邮件,并将其数据保存在mongoatlas数据库中,我使用mongoose。

  1. 准备altas mongo url连接到他们的数据库。您需要在netlify网站上添加环境变量,在已部署项目的设置中,或者您可以在部署之前添加环境变量。
  2. 在项目的根目录下:
  • 创建文件夹db>conntectDb.js文件

  • 在connectdb .js文件

    const mongoose = require('mongoose');
    const connectDb = async (url) => {
    //Here you can observe that url of mongo atlas will show once
    //Check this in netlify functions panel after you deploy your page
    //Observe it when you send form using url netlify function
    console.log(url, 'url to mongo atlas, connectDb');
    await mongoose.connect(url);
    };
    module.exports = connectDb;
    
  • 创建文件夹模型>email.js文件

  • 在email.js文件中创建email schema

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    const emailSchema = new Schema({
    name: {
    type: String,
    required: true,
    },
    email: {
    type: String,
    required: true,
    },
    message: {
    type: String,
    required: true,
    },
    });
    module.exports = mongoose.model('Email', emailSchema);
    
  • 创建文件夹netlify>文件夹函数>email.js文件

  • 这里保留netlify函数

  • 关于在项目中添加netlify函数时文件夹结构的信息,您可以在这里找到:https://docs.netlify.com/functions/build-with-javascript/

  • 在email.js文件

    const mongoose = require('mongoose');
    const connectDb = require('../../db/connectDb');
    const Email = require('../../models/email');
    connectDb(process.env.REACT_APP_DB);
    //Make connection with mongoose to mongo atlas outside handler
    exports.handler = async function (event) {
    //Observe state connection for mongoose in
    //Netlify functions panel on their website when you deploy your   page
    console.log(mongoose.connection.readyState, 'Ready state email');
    const body = JSON.parse(event.body);
    const newEmail = await Email.create(body);
    return{
    statusCode: 200,
    body: JSON.stringify({ value: newEmail }),
    };
    };
    

注意:我在函数处理程序之外添加了连接猫鼬(connectDb)。

  • 第一次mongoose.connection.readyState将显示'2',表示'连接'数据库
  • 稍后将显示'1',表示'已连接'
  • 这可以防止所有的时间连接到数据库。
  • Info:检查连接状态
  • https://mongoosejs.com/docs/api/connection.html connection_Connection-readyState
  • 你可以在netlify项目的函数面板中观察日志,当你调用url这个函数时,

在你的组件中的react(在这个例子中我使用react):

  • 创建表单,输入姓名,电子邮件,消息
  • 使用例如fetch api发送请求
  • 发送POST http请求
  • 使用此url const url = '/netlify/functions/email';
  • 如果你遵循我在这个例子中的文件夹结构

。我希望这对你有帮助。

最新更新