但我可以在本地写入它"/>
Lambda不会写入mongodb,但我可以在本地写入它
我使用的是通过服务器less部署到aws的aws lambda,并使用连接字符串写入mongodb。当在本地调用lambda时,所有这些都有效,并且我检查了一下,看我正在本地写入到lambda的数据的格式与我正在写入实时lambda的格式相同,而且确实如此。我不知道怎么了,因为我没有收到错误。
"use strict";
module.exports.addNewMenuItem = async event => {
var MongoClient = require('mongodb').MongoClient;
const options = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000,
useUnifiedTopology: true ,
useNewUrlParser: true
};
;
console.log(process.env.MONGO_CONNECTION_STRING)
console.log("eb", event.body)
const { coffee_type, coffee_subtype, business_id } = event.body
const client = new MongoClient(process.env.MONGO_CONNECTION_STRING, options);
await client.connect(clientConnectError => {
if (clientConnectError) {
console.log("client connection error", clientConnectError)
}
client.db("Coffee2Go").collection("MenuItems").insertOne({ coffee_type, coffee_subtype, business_id }, function (writeError, result) {
if (writeError) {
console.log("db error", writeError)
}
console.log("added the new menu item successfully")
});
});
return {
"body": "menu item added successfully",
"headers": {
"Access-Control-Allow-Origin": "*"
},
"statusCode": 200
};
};
回答如下:如您所见,您的函数仅需要6.78毫秒即可完成,这意味着该函数没有等待查询完成,它只是立即返回一个对象。按下return
时该功能将停止。
在您的本地端,当函数获得return
时,Mongodb查询仍在运行。但是它在lambda端不起作用,当功能停止时,它将停止所有进程。
主要原因是您将async/await
语法与callback
的MongoClient
语法混合。
await client.connect(clientConnectError => { // does not make sense
作为Mongodb document,您可以将其方法用作Promises。
"use strict";
module.exports.addNewMenuItem = async event => {
var MongoClient = require('mongodb').MongoClient;
const options = {
socketTimeoutMS: 30000,
keepAlive: true,
reconnectTries: 30000,
useUnifiedTopology: true,
useNewUrlParser: true
};
;
console.log(process.env.MONGO_CONNECTION_STRING)
console.log("eb", event.body)
const { coffee_type, coffee_subtype, business_id } = event.body
const client = new MongoClient(process.env.MONGO_CONNECTION_STRING, options);
try {
await client.connect() // return Promise if no callback passed
await client.db("Coffee2Go").collection("MenuItems").insertOne({ coffee_type, coffee_subtype, business_id })
console.log("added the new menu item successfully")
} catch(err) {
console.log("db error", writeError)
// As your original logic. The error will not effect to result of the function.
// But, I think this is not a good flow, you need tell to your client that process get back an error in this case
return {
"body": JSON.stringify({
message: "Insert item error",
error: err.message
}),
"headers": {
"Access-Control-Allow-Origin": "*"
},
"statusCode": 500 // instead of 200 - success
};
}
return {
"body": "menu item added successfully",
"headers": {
"Access-Control-Allow-Origin": "*"
},
"statusCode": 200
};
};
更多推荐
Lambda不会写入mongodb,但我可以在本地写入它
发布评论