【发布时间】: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?). Runningcallback(updateWord)is very similar tothrow updateWord. You should probably justawaitthe update and then invoke the callback with no args.
标签: javascript node.js amazon-web-services lambda