mongo / node TypeError:回调不是查询函数

时间:2016-01-23 17:09:19

标签: node.js mongodb express coffeescript

我正在尝试确定集合中是否存在文档。如果文档存在,我希望向对象添加属性“unread = false”。如果它不存在,我希望插入文档并向对象添加“unread = true”。

以上咖啡脚本中的代码如下:

functionxyz = (db, uid, events, done) ->
async.each events, (eventobj) ->
    if db.Event.find(eventobj).count() > 0
        eventobj.unread = false
    else
        db.Event.insert eventobj
        eventobj.unread = true
done null, events

我收到的错误是

/Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/connection/base.js:246
        throw message;      
        ^

TypeError: callback is not a function
  at /Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/collection/commands.js:55:5
  at /Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/db.js:1197:7
  at /Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/db.js:1905:9
  at Server.Base._callHandler (/Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/connection/base.js:453:41)
  at /Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/connection/server.js:488:18
  at [object Object].MongoReply.parseBody (/Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
  at [object Object].<anonymous> (/Users/owner/Desktop/coding challenge/repo/node_modules/mongodb/lib/mongodb/connection/server.js:446:20)
  at emitOne (events.js:77:13)
  at [object Object].emit (events.js:169:7)
  at [object Object].<anonymous> (/Users/owner/Deskto

有人可以向我解释这个错误发生的原因以及潜在的解决方案可能是什么?

1 个答案:

答案 0 :(得分:2)

MongoDB Native Driver for Node遵循异步函数的Node.js约定,即每个方法都接收回调函数作为最后一个参数。因此,应该将您的函数重写为:{/ p>,而不是db.collection.find(query).count()

db.collection.find(query).count( function(err, count){ // do stuff here } 

参数count会捕获您的查询结果。

您还可以将功能简化为db.collection.count(query, function(err, count){}

您的插入函数也应遵循相同的约定,使用形式为function(err, res){}的回调函数作为最后一个参数。

我建议您查看MongoDB Native Driver Docs以获取更多信息。

编辑以在CoffeeScript中提供示例: 这是用CoffeeScript语法重写的函数。

db.Event.count(eventobj, (err, count) ->
    // do stuff