【问题标题】:mongodb pass arguments to collection findmongodb 将参数传递给集合查找
【发布时间】:2017-12-04 12:03:03
【问题描述】:

我正在尝试将函数的参数传递给 mongodb 集合查找。像这样:

async find() {
  try {
    return await db.collection('users').find.apply(null, arguments);
  } catch(err) {
    console.error(err);
  }
}

返回

TypeError: Cannot read property 's' of null at Collection.find (/localpath/node_modules/mongodb/lib/collection.js:282:22)

我可以跑

await db.collection('users').find()

并且正在返回游标。因此,连接和收集已正确设置。

我在这里没有得到什么?

【问题讨论】:

    标签: javascript node.js mongodb arguments


    【解决方案1】:

    你申请的第一个参数是空的,它不能是。

    我建议你将引用作为第一个参数传递给apply,或者解开参数:

    await db.collection('users').find(...arguments)
    

    澄清 null 作为apply 的第一个参数的影响...

    // will log "hello"
    ({foo:function(){console.log(this.bar)}, bar:'hello'}).foo()
    
    // will log undefined
    ({foo:function(){console.log(this.bar)}, bar:'hello'}).foo.apply(null)
    

    【讨论】:

    • 空有效。试试这个:`function b(args) { console.log('args', args); };函数 a() { b.apply(null, arguments); } a('test');` 当我使用 rest 参数而不将第一个参数设置为 null 时,我仍然得到同样的错误。抱歉无法格式化代码。根据“帮助”,反引号应在注释中生成格式化代码,但事实并非如此。
    • 你按照我说的试过了吗?随着论点的展开?您在这里所做的唯一区别是您通过应用 null 来抑制上下文。
    • ofc 它在您的示例中有效,您没有参考上下文。这不是语法问题,它取决于使用的代码。让我更新答案以澄清
    • 是的,当然,正如你所说。正如我所写(引用自己的话):“当我使用 rest 参数而不将第一个参数设置为 null 时,我仍然会遇到同样的错误。”你要,我可以截图。
    • 那么你将第一个参数设置为什么?
    猜你喜欢
    • 2023-03-24
    • 2020-03-17
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多