通过mongoose连接到mongodb不再在无服务器nodejs函数中工作

zzlelutf  于 2023-05-13  发布在  Go
关注(0)|答案(1)|浏览(161)

在我的无服务器应用程序中,我正在连接到MongoDB数据库。这已经在我的应用程序几个月了,但就在昨天停止工作。但是,当使用serverless-offline时,它在本地工作。我的连接代码看起来像这样:

// dabatase.js
const mongoose = require('mongoose');

const connect = async (uri) => {
  try {
    mongoose.set("strictQuery", true)

    mongoose.connect(uri)
  
    mongoose.connection.on('connected', () => {
      console.log("Connected to database...");
    });
    
    mongoose.connection.on('disconnected', () => {
      console.log('Disconnected from database...');
    });
    
    process.on('SIGINT', () => {
      mongoose.connection.close(() => {
        console.log("Connection closed...");
        
        process.exit(0);
      });
    });
  } catch(error) {
    console.log(error)
  }
}

module.exports.connect = connect;

在我的函数中,我像这样连接到数据库:

const User = require("../models/User")
const bcrypt = require("bcryptjs")
const _ = require("lodash")
const jwt = require("jsonwebtoken")
const { connect } = require("../database")

connect(process.env.DATABASE)

module.exports.handler = async (event) => {
  let headers = {
    "Access-Control-Allow-Origin": event.headers.origin,
    "Access-Control-Allow-Credentials": true
  }

  ...other code
}

这一直有效,现在我在生产中尝试命中我的端点时得到502和CORS错误。事情似乎在本地工作得很好,但当部署到AWS时,我总是遇到这个错误。以下是cloudwatch日志:

cl25kdpy

cl25kdpy1#

在serverless中,您必须首先检查连接是否存在,请参阅mongoose指南:https://mongoosejs.com/docs/lambda.html
我个人使用connect,它从来没有让我失望过:

import { config } from "dotenv";
import mongoose, { Mongoose } from "mongoose";

config();

let conn: null | Promise<Mongoose> = null;

export const connect = async function (dbName?: string) {
  const parsedDbName = dbName || process.env.DB_NAME;
  const uri = `mongodb+srv://admin:${process.env.MONGODB_PASSWORD}@adyproduction.5cosb.mongodb.net/${parsedDbName}?retryWrites=true&w=majority`;

  console.log("Connecting to MongoDB...");

  mongoose.set("strictQuery", false);
  if (conn == null) {
    conn = mongoose
      .connect(uri, {
        serverSelectionTimeoutMS: 5000,
      })
      .then(() => mongoose);

    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn;
  }

  return conn;
};

也要确保在处理程序上连接,而不是在外部函数中,像这样:

import { connect } from "./helpers/mongo-connect";

const handler = async (event) => {
  await connect();

  // Rest of the code
}

相关问题