[英]How to properly handle promise using nodejs and mongodb
我已將我的 nodejs 應用程序配置為使用 mongodb。 我可以成功連接並將數據添加到我的 mongodb 實例。 我的應用程序配置如下(敏感信息已編輯):
// mongoDB configs
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@codigoinitiative.3klym.mongodb.net/<collection>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
//express configs
const app = express();
const express = require('express');
//mongo endpoint
app.get('/mongo', (req, res) => {
invoke().then(() => res.send('all good')).catch(err => console.log('invoke error:', err))
});
//mongodb access/logic
async function invoke() {
console.log('connecting')
return new Promise((resolve, reject) => {
client.connect(err => {
if(err) return reject(err)
console.log('connected.');
const collection = client.db("CodigoInitiative").collection("Registered");
//create document to be inserted
const pizzaDocument = {
name: "Pizza",
shape: "round",
toppings: [ "Pepperoni", "mozzarella di bufala cheese" ],
};
// perform actions on the collection object
const result = collection.insertOne(pizzaDocument);
console.log(result.insertedCount);
// //close the database connection
client.close();
});
});
}
如果我點擊/mongo
端點,披薩文檔會在數據庫上創建就好了,但我注意到連接永遠不會關閉; 意思是, /node
端點永遠不會發送“all good”字符串作為響應。 此外,對/node
的任何后續請求都會引發以下錯誤:
connecting
the options [servers] is not supported
the options [caseTranslate] is not supported
the options [dbName] is not supported
the options [srvHost] is not supported
the options [credentials] is not supported
connected.
undefined
(node:94679) UnhandledPromiseRejectionWarning: MongoError: topology was destroyed
at executeWriteOperation (/Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/core/topologies/replset.js:1183:21)
at ReplSet.insert (/Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/core/topologies/replset.js:1252:3)
at ReplSet.insert (/Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/topologies/topology_base.js:301:25)
at insertDocuments (/Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/operations/common_functions.js:259:19)
at InsertOneOperation.execute (/Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/operations/insert_one.js:26:5)
at executeOperation (/Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/operations/execute_operation.js:77:17)
at Collection.insertOne (/Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/collection.js:517:10)
at /Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node.js:154:39
at /Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/utils.js:677:5
at /Users/vismarkjuarez/Documents/GitLab/CodigoInitiative/node_modules/mongodb/lib/mongo_client.js:226:7
(node:94679) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:94679) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
看來我沒有正確處理 promise 和異步調用,並且在某處缺少.catch()
,但我不確定在哪里。 我在哪里搞砸了?
你沒有看到all good
原因是因為這個塊
return new Promise((resolve, reject) => {
從來沒有真正解決。 您應該通過調用resolve(...)
來解決它。 只有這樣你的invoke().then(() =>...
才會被觸發。
所以我會讓那個塊看起來像這樣:
...
...
// perform actions on the collection object
const result = collection.insertOne(pizzaDocument);
console.log(result.insertedCount);
// //close the database connection
client.close();
resolve('ok')
...
...
但更一般地說,您當然希望 mongo 連接在請求到來時准備好,而不是每次都打開一個新連接。
另外,就個人而言,我會像這樣簡化您的代碼。
//mongo endpoint
app.get('/mongo', invoke);
//mongodb access/logic
const invoke = (req, res) => {
client.connect(err => {
if(err) return res.json(err)
console.log('connected.');
const collection = client.db("CodigoInitiative").collection("Registered");
//create document to be inserted
const pizzaDocument = {
name: "Pizza",
shape: "round",
toppings: [ "Pepperoni", "mozzarella di bufala cheese" ],
};
// perform actions on the collection object
const result = collection.insertOne(pizzaDocument);
console.log(result.insertedCount);
// //close the database connection
client.close();
res.json({msg: 'all good'})
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.