一切正常,直到我将db.collection函数放入“ com”中。现在,他返回错误“无法设置未定义的属性'collection'”。为什么会产生这种效果?
"use strict";
var MongoClient = require('mongodb').MongoClient;
var mongoUrl = "mongodb://localhost:27017/";
var database = 'ks';
function DB(command, collection, args, call) {
this.collection = collection
MongoClient.connect(mongoUrl, {useNewUrlParser: true}, (err, dbo) => {
if (err) throw err;
var db = dbo.db(database);
if (err) throw err;
var com = {
find: db.collection(this.collection).find(args).toArray((err, data) => {
if(err) throw err;
call(data);
})
}
dbo.close();
return com['find'];
})
}
// console.log(find('characters',{name: "Dawid"}))
DB('characters',{name: "Dawid"}, (call) => {
console.log(call)
})
答案 0 :(得分:-2)
您是否尝试过将其绑定到变量并像这样传递它?
var that = this;
... db.collection(that.collection)...
当您将this
打包到JS对象中时,可能会丢失var that = this
。使用this
,您可以将当前上下文的db.collection.
绑定到变量,并将正确的引用传递给this
当然,可能有更好的方法来捕获downloadCSVData() {
axios({
url: '/downloadCSVData',
method: 'GET'
}).then((response) => {
console.log(response)
});
}
,但这是另一个问题的另一个答案。
在查看代码时突然想到的第一件事似乎就是这种问题。