我已经将我的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
endpoint,那么pizza文档就会很好地在数据库中创建,但我注意到连接从未关闭;这意味着/node
endpoint从不将“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和async调用,并且在某个地方缺少.catch()
,但我不确定是在哪里。我这是在搞什么鬼?
您没有看到all good
的原因是这个块
return new Promise((resolve, reject) => {
从未真正解决过。您应该通过调用resolve(...)
来解析它。只有这样,您的才会调用()。然后(()=>...
会被触发。
所以我会让这个块看起来像这样:
...
...
// 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'})
});
}