【问题标题】:Why does the "TypeError: client.db is not a function" appear on Node.js and how do I fix it?为什么 Node.js 上会出现“TypeError:client.db 不是函数”,我该如何解决?
【发布时间】:2020-09-30 12:53:23
【问题描述】:

在我偶然发现这个 TypeError 之前,我一直在关注我的业务。我已尽力弄清楚,但代码在我的方法中不起作用。

const express = require("express");
const bodyParser = require("body-parser");
const mongoClient = require("mongodb").MongoClient;
const objectId = require("mongodb").ObjectID;
require("dotenv/config");

let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:true }));
app.get('/', (req, res) => {

app.listen(4000, () => {
console.log("It's connected to the server!");
mongoClient.connect(process.env.DB_CONNECTION, { useNewUrlParser:true, useUnifiedTopology: true }, (client, err) => {
    if (err) {
        throw error
    };
    const dB = client.db(process.env.DB_NAME); //Not a function, why?
    dB.collection("cookie");
    console.log(`Connected to "${process.env.DB_NAME}" !`);
});

});

我希望我能得到一些关于如何正确解决问题的好建议。 :)

【问题讨论】:

    标签: jquery node.js mongodb express


    【解决方案1】:

    mongoClient.connect 的回调有错误的参数顺序。

    (client, err) => {...} 应该是(err, client) => {...}

    它要么收到一个真正的错误,要么收到null,但它们中的任何一个都不应该有一个名为db的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-22
      • 2020-09-14
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多