mongo / node TypeError:callback不是查询中的函数
我试图确定一个文件是否存在于一个集合中。 如果文档存在,我希望添加一个属性“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
有人可以向我解释这个错误发生的原因以及可能的解决scheme是什么?
Node的MongoDB本地驱动程序遵循Node.js约定的asynchronous函数,即每个方法接收一个callback函数作为最后一个参数。 因此,而不是db.collection.find(query).count()
,您的函数应该被重写为:
db.collection.find(query).count( function(err, count){ // do stuff here }
参数count
捕获您的查询的结果。
你也可以将函数简化为db.collection.count(query, function(err, count){}
。
您的插入函数也应遵循相同的约定,使用函数formsfunction(err, res){}
的callback函数作为最后一个参数。
我build议查看MongoDB本地驱动程序文档了解更多信息。
编辑为在CoffeeScript中提供示例:这是用CoffeeScript语法重写的函数。
db.Event.count(eventobj, (err, count) -> // do stuff