You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lambda函数更新MongoDB时出现[object Promise]错误求解决

问题:Lambda函数更新MongoDB时返回[object Promise]错误

运行Lambda函数从数组随机选取对象更新MongoDB唯一文档时,返回如下错误:

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

以下是我的代码:

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)
    
    };

问题分析与修复

错误原因

  1. 未等待异步操作完成:db.collection.updateOne()是异步方法,执行后会返回一个Promise。直接将这个Promise传给callback,Lambda无法解析Promise对象,就会抛出[object Promise]错误。
  2. _id格式错误:把"ObjectId('redacted')"作为字符串传入查询条件,MongoDB不会将其识别为有效的ObjectId类型,导致更新无法匹配到目标文档。

修复后的代码

const MongoClient = require("mongodb").MongoClient;
// 引入ObjectId构造函数处理_id
const { ObjectId } = require("mongodb");

const MONGODB_URI = "Removed for Privacy";

let cachedDb = null;

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

  const client = await MongoClient.connect(MONGODB_URI);
  const db = client.db("redacted"); // client.db是同步方法,无需await

  cachedDb = db;
  return db;
}


exports.handler = async (event, context) => {
  context.callbackWaitsForEmptyEventLoop = false;

  try {
    const db = await connectToDatabase();
    const WORDS = [ { "word": 'exampleWord', "description": 'exampleDescription' }];
    const wotd = WORDS[Math.floor(Math.random() * WORDS.length)];
    
    // 等待updateOne执行完成,同时正确转换_id类型
    const updateResult = await db.collection('wordoftheday').updateOne(
      {"_id": ObjectId('redacted')},
      {$set: {
        "word": wotd.word,
        "description": wotd.description
      }}
    );

    // async handler直接返回结果即可,无需callback
    return {
      statusCode: 200,
      body: JSON.stringify({
        message: "更新成功",
        matchedCount: updateResult.matchedCount,
        modifiedCount: updateResult.modifiedCount
      })
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify({
        error: error.message
      })
    };
  }
};

关键修改点

  • 引入ObjectId构造函数,将字符串形式的_id转换为MongoDB可识别的类型。
  • 使用await等待updateOne异步操作完成,获取实际的更新结果。
  • 利用async函数特性直接返回结果,替代传统callback写法(Lambda对async handler的支持更简洁)。
  • 添加try-catch块捕获异常,返回更清晰的错误信息。

内容的提问来源于stack exchange,提问作者mannymcfly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 11:45:30