javascript - 在 MongoDB 3.6 NodeJS 驱动程序中断言?以及在使用promise实现时如何使用assert?

标签 javascript node.js mongodb reactjs express

在 MongoDB 3.6 驱动程序中,当我通过回调连接到 mongodb 主机时,我遵循快速入门指南:

来自示例:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

assert函数的用法是什么? 如果在 promise 方法中实现,我该如何使用断言?

在我的项目中,我不知道应该将“assert”放在函数的什么位置。 下面是我的 server.js

import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import { MongoClient } from 'mongodb';
import assert from 'assert';

const app = express();
const MONGO_URL = 'mongodb://localhost:27017';
const dbName = 'inventory';
app.use(express.static('../public'));
app.use(bodyParser.json());

app.get('/api/issues', (req, res) => {
  db.collection('issues').find().toArray().then(issues => {
    const metadata = { total_count: issues.length };
    res.json({ _metadata: metadata, records: issues })
  }).catch(error => {
    console.log(error);
    res.status(500).json({ message: `Internal Server Error: ${error}` });
  });
});

let db;
MongoClient.connect(MONGO_URL).then(client => {
  db = client.db(dbName);

  app.listen(4000, () => {
    console.log('App started on port 4000');
  });
}).catch(error => {
  console.log('ERROR:', error);
});

最佳答案

当您使用回调样式时,当发生错误时,err 参数将出现此类错误,因此不会为null

所以断言:

MongoClient.connect(url, function(err, client) {
  assert.equal(null, err); // guarantees err is null, so no error has occurred

存在以确保 err 在代码继续之前为 null


在**Promise 风格**中,您不需要断言。如果发生错误,将调用 .catch 。

因此,您需要做的是在您的 promise 中声明一个 .catch(),您已经在其中做了:

MongoClient.connect(MONGO_URL).then(client => {
  ...
}).catch(error => {                     // this catch will be called when an error occurs
  console.log('ERROR:', error);
});



注意:最后,如果您使用 async/await,则必须声明 try/catch block 的 catch来处理错误。例如

(async () => {
    try {
        let client = await MongoClient.connect(MONGO_URL)
        ...
    } catch(error) {                     // this catch will be called when an error occurs
      console.log('ERROR:', error);
    }
})();

关于javascript - 在 MongoDB 3.6 NodeJS 驱动程序中断言?以及在使用promise实现时如何使用assert?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49972129/

相关文章:

javascript - 我可以用另一个 regExp 替换 regExp 吗?

javascript - node.js - 使用 arrayFilter 在 mongoose findOneandUpdate 中嵌套数组

javascript - angular js 中 $scope 的 console.log

javascript - 如何将复选框值导出到 csv 文件?

javascript - 对于 Angular 谷歌地图,我如何删除多段线?

node.js - 在Webpack和Node.js中使用vscode调试器

javascript - 如何使用使用 Passport.js 的远程 NodeJS API 对客户端 Web 应用程序进行身份验证和授权

node.js - 如何使用mongodb更新普通数组中的数据

python - mongoengine中的复合主键

java - mongodb打开连接问题