node.js - 第一次写monodb app时出错
问题描述
因此,这是任何人都可以解释为什么此代码给出此错误的代码。
... const { MongoClient } = require('mongodb').Mongoclient; 常量断言 = 要求('断言');
const url = "mongodb://localhost:27017";
const dbName = 'fruitsdb';
const client = new MongoClient(url, {
useUnifiedTopology: true,
useNewUrlParser: true
});
client.connect(function(err) {
assert.equal(null,err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
}); ...
const { MongoClient } = require('mongodb').Mongoclient; ^
TypeError:无法解构MongoClient
“未定义”或“空”的属性。
但这段代码没有给出错误。
...
const { MongoClient } = require('mongodb');
const assert = require('assert');
const url = "mongodb://localhost:27017";
const dbName = 'fruitsdb';
const client = new MongoClient(url, {
useUnifiedTopology: true,
useNewUrlParser: true
});
client.connect(function(err)
{
assert.equal(null,err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
请也解释一下代码,我是新手,刚开始,你能解释一下代码是如何工作的。
解决方案
查看此示例,当您使用 {“property”} = Object 时,您选择了 Object 中存在的一个属性。
const data = {
firstName: "ravi",
lastName: "kumar",
friend: {
firstName: "erfan",
lastName: "hp",
}
}
const { firstName } = data; // show ravi
const { firstName } = data.friend; // show erfan
我们在 require('mongodb') 中有 MongoClient 属性
但我们在 require('mongodb').MongoClient 中没有 MongoClient 属性
推荐阅读
- java - 如何让一维数组接受多个字符串值?
- java - 即使用户不使用它,在我的应用程序上处理 ACTION_PACKAGE_ADDED 意图的更好方法是什么?
- javascript - 我的函数和调用者有什么问题?按钮提示功能
- python - 为什么 unittest 不能识别 SQLAlchemy 数据类型?
- javascript - 文档已创建但响应为空
- javascript - onClick Modal 使整个页面消失
- javascript - 浏览器中的静态页面盖茨比?
- r - 有没有办法将带有表情符号的文本写入 Excel 或 Google 表格?
- javascript - AJAX 冻结网页,并发出警告说浏览器变慢
- mongodb - 链接具有不同坐标的两个地理空间查询