【问题标题】:Have an error while writing monodb app for the first time第一次写mongodb app时出错
【发布时间】:2021-07-14 13:15:16
【问题描述】:

所以,这是任何人都可以解释为什么此代码会出现此错误的代码。

... const { MongoClient } = require('mongodb').Mongoclient; 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();

}); ...

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.js mongodb


    【解决方案1】:

    看看这个例子,当你使用 { "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 属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-15
      相关资源
      最近更新 更多