首页 > 解决方案 > 为什么 func 不是 node.js 中的函数?

问题描述

我正在学习mongodb,在书中,有一个代码

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) {
  MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    else {
      console.log("connected");
      func(db);
      db.close();
    }
  });
};

我运行这段代码,但抛出错误TypeError: func is not a function,我用谷歌搜索,但有很多这样的代码,我的 mongodb 版本是 4.0,node.js 版本是 9.10,有什么想法吗?

标签: node.jsmongodb

解决方案


无论func您传递什么,都必须是一个函数。

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://127.0.0.1:27017/testdb";
module.exports = function (func) { //func must be function, dont pass just a variable
  MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    else {
      console.log("connected");
      func(db);
      db.close();
    }
  });
};

推荐阅读