首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用nodejs和mongodb正确处理promise

如何使用nodejs和mongodb正确处理promise
EN

Stack Overflow用户
提问于 2021-02-05 11:31:47
回答 1查看 87关注 0票数 0

我已经将我的nodejs应用程序配置为使用mongodb。我可以成功连接mongodb实例并将数据添加到mongodb实例中。我的app配置如下(敏感信息已被编辑):

代码语言:javascript
运行
复制
// 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的任何后续请求都会抛出以下错误:

代码语言:javascript
运行
复制
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(),但我不确定在哪里。我哪里搞砸了?

EN

回答 1

Stack Overflow用户

发布于 2021-02-05 11:38:56

您看不到all good的原因是因为这个块

代码语言:javascript
运行
复制
return new Promise((resolve, reject) => {

从来没有真正解决过。您应该通过调用resolve(...)来解决此问题。只有到那时,你的invoke().then(() => ...才会被触发。

所以我会让这个块看起来像这样:

代码语言:javascript
运行
复制
...
...
        
      // perform actions on the collection object
      const result = collection.insertOne(pizzaDocument);
      console.log(result.insertedCount);
        
      // //close the database connection
      client.close();
      resolve('ok')
...
...

但更普遍的是,您肯定希望mongo连接在请求到来时准备就绪,而不是每次都打开一个新的连接。

另外,就我个人而言,我会这样简化你的代码。

代码语言:javascript
运行
复制
//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'})
        });
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66057190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档