【问题标题】:Lambda Function Errors When Updating MongoDBLambda Function Errors When Updating MongoDB
【发布时间】:2022-12-01 13:31:14
【问题描述】:

I am new to Web Dev and I am a bit in over my head. I am trying to run a task using a Lambda function to grab a random object from an array of objects and uppdate the only document in my MongoDB Collection

currently, it is returning this error

{
  "errorType": "object",
  "errorMessage": "[object Promise]",
  "trace": []
}

If someone could also help me understand why that would be great!

Here is what I am working with


const MongoClient = require("mongodb").MongoClient;

const MONGODB_URI =
  "Removed for Privacy";

let cachedDb = null;

async function connectToDatabase() {
  if (cachedDb) {
    return cachedDb;
  }

  // Connect to our MongoDB database hosted on MongoDB Atlas
  const client = await MongoClient.connect(MONGODB_URI);

  // Specify which database we want to use
  const db = await client.db("redacted");

  cachedDb = db;
  return db;
}


exports.handler = async (event, context, callback) => {

  context.callbackWaitsForEmptyEventLoop = false;

  const db = await connectToDatabase();

    const WORDS = [ { "word": 'exampleWord', "description": 'exampleDescription' }]
    
    let wotd = WORDS[Math.floor(Math.random() * WORDS.length)]
    
    
    let updateWord = db.collection('wordoftheday').updateOne({"_id":"ObjectId('redacted')"},{$set: {
      "word": wotd.word,
      "description": wotd.description}})
  
    callback(updateWord)
    
    };


【问题讨论】:

  • Traditionally, callbacks in nodejs are of the form callback(err?). Running callback(updateWord) is very similar to throw updateWord. You should probably just await the update and then invoke the callback with no args.

标签: javascript node.js amazon-web-services lambda


【解决方案1】:

Try adding await statement to wait for database update record and return the updated record

let updateWord = await db.collection('wordoftheday').updateOne({"_id": new ObjectId('redacted')},{$set: {
      "word": wotd.word,
      "description": wotd.description}})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多