[英]Assert in MongoDB 3.6 NodeJS driver? And how to use assert when using promise implementation?
In MongoDB 3.6 driver, when I connect to mongodb host by callback, I follow the quickstart guide:在 MongoDB 3.6 驱动程序中,当我通过回调连接到 mongodb 主机时,我遵循快速入门指南:
From the example:从例子:
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();
});
What is the assert function usage?断言函数的用法是什么? And if implement in promise method, how can I use assert?
如果在promise方法中实现,我该如何使用assert?
From my project, I don't know where I should put "assert" to the function.从我的项目中,我不知道应该将“断言”放在函数的哪个位置。 Below is my server.js
下面是我的 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);
});
When you use callback style, when an error occurs, the err
argument will have such error and thus will not be null
.当您使用回调样式时,当发生错误时,
err
参数将出现此类错误,因此不会为null
。
So that assertion:所以这个断言:
MongoClient.connect(url, function(err, client) {
assert.equal(null, err); // guarantees err is null, so no error has occurred
Exists to make sure err
is null
before the code continues.存在以确保在代码继续之前
err
为null
。
So, what you needed to to was to declare a .catch()
in your promise, which you already do in:所以,你需要做的是在你的承诺中声明一个
.catch()
,你已经这样做了:
MongoClient.connect(MONGO_URL).then(client => { ... }).catch(error => { // this catch will be called when an error occurs console.log('ERROR:', error); });
Note: Lastly, if you used async
/ await
you had to declare a catch
of a try/catch
block to handle the errors.注意:最后,如果你使用
async
/ await
你必须声明一个try/catch
catch
的 catch 来处理错误。 Eg例如
(async () => { try { let client = await MongoClient.connect(MONGO_URL) ... } catch(error) { // this catch will be called when an error occurs console.log('ERROR:', error); } })();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.