首页 > 解决方案 > 第一次写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();

});

请也解释一下代码,我是新手,刚开始,你能解释一下代码是如何工作的。

标签: node.jsmongodb

解决方案


查看此示例,当您使用 {“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 属性


推荐阅读