javascript - 实例化导出类的属性时出错

标签 javascript node.js mongodb express

我正在尝试实例化一个导出的类,但出现以下错误:

TypeError: Cannot set property '_db' of undefined

我是如何创建和导出类的:

const mongodb = require('mongodb').MongoClient
const url = 'mongodb://localhost/via'
const collection = 'images'

module.exports = class DB {
    constructor() {
        mongodb.connect(url, function(err, db) {
            if (err) throw err

            this._db = db.db('via') //Error line

            this._db.createCollection(collection, function(err, res) {
                if (err) throw err
                console.log(`Collection ${collection} created successfully.`)
            })
        })
    }
}

我是如何实例化的:

const db = require('../db/images')
let database = new db();

我试过在使用它之前创建变量,但无济于事。我做错了什么?

最佳答案

这里的问题是你的构造函数在你调用 mongodb.connect 的地方使用普通函数回调 -> function(err, db) 这意味着函数内部的任何东西this 不会指向您的类。

一个简单的解决方案是使用箭头函数,将 function(err, db) { 替换为 (err, db) => {

就我个人而言,我不是箭头函数的忠实粉丝,在某些方面我认为它类似于 with 语句,很容易失去上下文。因此,与箭头函数和普通函数一起使用的另一种方法是捕获作用域。

例如->

module.exports = class DB {
    constructor() {
        const thisDB = this;
        mongodb.connect(url, function(err, db) {
            if (err) throw err

            thisDB._db = db.db('via') //Error line

            thisDB._db.createCollection(collection, function(err, res) {
                if (err) throw err;
                //bonus, thisDB will work here too.
                console.log(`Collection ${collection} created successfully.`)
            })
        })
    }
}

上面很明显 thisDB 也指向什么,当进行更深层次的回调时,它仍然有效,如上所示,我在上面提到了 bonus,thisDB 也可以在这里工作

关于javascript - 实例化导出类的属性时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49481716/

相关文章:

node.js - 在不下载整个文件的情况下读取和解析 S3 中的 CSV 文件

mysql - 无法从 Node 但从终端访问mysql容器

javascript - 超过26字节的CRC计算

C# mongo 附近查询无法找到 $geoNear 的索引

javascript - 将 groupFooterTemplate 显示为 Kendo Grid 的整个页脚行

javascript - Chrome 扩展程序的内容脚本如何确定注入(inject)页面的引荐来源网址?

python - mongoDB:PyMongo 中包含单个字母的字符串的全文查询

c# - mongoDB: C# driver V2 如何更新嵌套集合中的项目

javascript - 表 html 到数组

javascript - 为什么使用 setInterval() 10 秒后收到第一个 AJAX