我对Alexa技能还很陌生。我掌握了“ hello world”的技能,并进行了一些HTTP请求。
现在,我正在尝试将我的技能与现有的MongoDB地图集集群联系起来。我的目标是从我的集群中检索一些数据,并运用其技能来响应询问Alexa某些问题的用户。
我认为我已经建立了与地图集的连接,但是当我尝试对数据库中的集合进行操作时,出现了“ MongoError:拓扑被破坏”错误。
正如我已经阅读的,问题可能出在AWS Lambda的工作流中。它处于无状态工作状态,当我尝试阅读集合时,连接可能已经断开,但我不知道该如何解决该问题。
这是我当前建立连接并仅打印文档计数的方法。我测试了如何移动客户端连接,但我总是遇到相同的错误。
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<USER>:<PASS>@<CLUSTER>?retryWrites=true";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("database").collection("data");
console.log(collection.countDocuments());
client.close();
});
const HelloWorldIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'HelloWorldIntent';
},
handle(handlerInput) {
const speechText = 'Hello World!';
return handlerInput.responseBuilder
.speak(speechText)
//.reprompt('add a reprompt if you want to keep the session open for the user to respond')
.getResponse();
}};
Promise {
<rejected> { MongoError: Topology was destroyed
at initializeCursor (/var/task/node_modules/mongodb-
core/lib/cursor.js:603:25)
at nextFunction (/var/task/node_modules/mongodb-core/lib/cursor.js:463:12)
at AggregationCursor.Cursor.next (/var/task/node_modules/mongodb-core/lib/cursor.js:763:3)
at AggregationCursor.Cursor._next (/var/task/node_modules/mongodb/lib/cursor.js:211:36)
at fetchDocs (/var/task/node_modules/mongodb/lib/operations/cursor_ops.js:217:12)
at toArray (/var/task/node_modules/mongodb/lib/operations/cursor_ops.js:247:3)
at executeOperation (/var/task/node_modules/mongodb/lib/utils.js:420:24)
at AggregationCursor.Cursor.toArray (/var/task/node_modules/mongodb/lib/cursor.js:824:10)
at countDocuments (/var/task/node_modules/mongodb/lib/operations/collection_ops.js:233:37)
at /var/task/node_modules/mongodb/lib/utils.js:437:24 name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} } }
答案 0 :(得分:0)
我用于连接MongoDb的其他AWS lambda函数也有类似的问题,我发现我们需要提供与Mongodb连接的其他参数,如下所述。
var options = {
server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }
};
mongoose.connect(secrets.db, options);
请尝试让我知道是否有帮助。
答案 1 :(得分:0)
'use strict'
var MongoClient = require('mongodb').MongoClient;
let cachedDb = null;
exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
function connectToDatabase(uri) {
if (cachedDb && cachedDb.serverConfig.isConnected()) {
console.log('=> using cached database instance');
return Promise.resolve(cachedDb);
}
const dbName = 'YOUR_DATABASE_NAME';
return MongoClient.connect(uri)
.then(client => { cachedDb = client.db(dbName); return cachedDb; });
}
尝试这种方式