【发布时间】:2017-10-18 06:00:59
【问题描述】:
function uploadVote(voter, vote){
MongoClient.connect(url, function(err, db){
if (err) throw err;
db.collection('testvote', function(err, collection) {
collection.find({"psid": voter}).toArray(function(err, result) {
if(!result[0]){
db.collection("testvote").insert({psid: "a", choice:0}, function(err, res) {
if (err) throw err;
console.log('insertone')
sendTextMessage(". ")
});
} else if(!result[0].choice){
db.collection("testvote").update({psid: voter}, {$set: {'choice': vote}}, function(err, res){
if (err) throw err;
sendTextMessage(". ")
})
} else{
sendTextMessage(voter, "!");
}
});
db.close();
});
})
}
您好,我正在开发一个让用户投票的 Facebook Messenger。在上面的代码中,我根本看不到语法错误。但是当这个函数被执行时,它总是出错:
/app/node_modules/mongodb/lib/utils.js:123
2017-05-18T12:09:19.856188+00:00 app[web.1]: process.nextTick(function() { throw err; });
2017-05-18T12:09:19.856188+00:00 app[web.1]: ^
2017-05-18T12:09:19.858765+00:00 app[web.1]: at ReplSet.insert (/app/node_modules/mongodb/lib/replset.js:398:18)
2017-05-18T12:09:19.858761+00:00 app[web.1]: MongoError: topology was destroyed
2017-05-18T12:09:19.858764+00:00 app[web.1]: at ReplSet.insert (/app/node_modules/mongodb-core/lib/topologies/replset.js:1025:47)
2017-05-18T12:09:19.858766+00:00 app[web.1]: at executeCommands (/app/node_modules/mongodb/lib/bulk/ordered.js:455:23)
2017-05-18T12:09:19.858766+00:00 app[web.1]: at OrderedBulkOperation.execute (/app/node_modules/mongodb/lib/bulk/ordered.js:508:10)
2017-05-18T12:09:19.858767+00:00 app[web.1]: at bulkWrite (/app/node_modules/mongodb/lib/collection.js:664:8)
2017-05-18T12:09:19.858768+00:00 app[web.1]: at Collection.insertMany (/app/node_modules/mongodb/lib/collection.js:534:44)
2017-05-18T12:09:19.858769+00:00 app[web.1]: at /app/index.js:121:41
2017-05-18T12:09:19.858768+00:00 app[web.1]: at Collection.insert (/app/node_modules/mongodb/lib/collection.js:836:15)
2017-05-18T12:09:19.858770+00:00 app[web.1]: at handleCallback (/app/node_modules/mongodb/lib/utils.js:120:56)
2017-05-18T12:09:19.858771+00:00 app[web.1]: at /app/node_modules/mongodb/lib/cursor.js:860:16
请帮我解决这个问题。
【问题讨论】:
-
我认为您的
db.close()调用可能会在传递给您的collection.find()调用的回调之前运行。这意味着在随后的insert()或update()调用开始时,数据库连接已经关闭 -
感谢您的帮助!那我应该如何编辑我的代码?
-
只需将 db.close() 放入回调中
-
您需要确保
db.close()仅在您完成后才被调用。您可以将它放在每个代码分支的末尾(即在sendTextMessage()的每个案例之后),或者将整个内容包装在一个 promise 中,然后在这些位置调用 resolve。我会在下面写一个答案。
标签: javascript node.js mongodb facebook-messenger