【问题标题】:Saving multiple Mongoose objects with asyncjs not working使用 asyncjs 保存多个 Mongoose 对象不起作用
【发布时间】:2013-03-25 18:41:30
【问题描述】:

我想在我的 mocha 测试中保存两个 Mongoose 对象 - 并在两者都成功时收到通知。我正在使用 asyncjs 库来实现这一点。

beforeEach (done) ->

  obj1 = new Person({ name: 'Jon' })
  obj2 = new Person({ name: 'Dan' })

  console.log obj1   # ... { name: 'Jon', _id: 4534534543512 }

  async.list([
    obj1.save
    obj2.save
  ]).call().end( (err, res) ->
    return done(err) if err
    done()
  )

您可以在 console.log 中看到 obj1 被设置为 MongoDB 文档 - 但是当我想使用 save 函数将它们持久保存到数据库时,尝试执行此操作时出现以下错误:

TypeError: Cannot read property 'save' of undefined

如果我用 say 替换 async.list 中的两个函数

console.log
console.log

代码执行得很好......另外,如果我像这样将这两个对象保存在 async.list 函数之外

obj1.save()
obj2.save()

它也执行得很好,没有错误。

我被难住了。

【问题讨论】:

  • 另外值得注意的是,有两个类似命名的异步库:async 和 asyncjs。上面的例子来自 asyncjs - 但更好的库是 async,而使用的方法是:parallel。

标签: node.js mongoose mocha.js


【解决方案1】:

这可能是因为没有使用预期的上下文 (this) 调用 save 函数。

当您传递像obj1.save 这样的“方法”时,async.list() 获取的引用仅指向function 本身,没有任何返回到obj1(或obj2)的链接.它类似于:

save = obj1.save
save() # `this` is `undefined` or `global`

要使用固定上下文传递,您可以bind 他们:

async.list([
  obj1.save.bind(obj1)
  obj2.save.bind(obj2)
]) # etc.

或者使用附加函数,以便在 member operator 之后调用它们:

async.list([
  (done) -> obj1.save(done),
  (done) -> obj2.save(done)
]) # etc.

【讨论】:

  • 成功了-谢谢-您结束了很多挫败感。我怀疑 this 周围有什么东西 - 并通过 call 方法将它传入 - 并调用了 this.obj1.save(),这显然不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-27
  • 2017-06-26
  • 2015-11-12
  • 2020-10-17
  • 2014-06-19
  • 1970-01-01
  • 2014-11-23
相关资源
最近更新 更多