node.js - mongo/Node 类型错误: callback is not a function on query

标签 node.js mongodb express coffeescript

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

上述 CoffeeScript 中的代码如下:

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

有人可以向我解释一下发生此错误的原因以及可能的解决方案吗?

最佳答案

Node 的 MongoDB native 驱动程序遵循异步函数的 Node.js 约定,即每个方法接收回调函数作为最后一个参数。因此,您的函数应重写为:

,而不是 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

关于node.js - mongo/Node 类型错误: callback is not a function on query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34966349/

相关文章:

node.js - 使用 id 更新用户角色的 API - Node

javascript - React Redux reducer 中缺少数组

javascript - 与 async.series 不同,async.applyEachSeries 无法引用 'this'

javascript - 我无法将 req.params.id 的输入使用到其他文件中存在的函数中

javascript - Node.js - 将值传递到其他页面

javascript - 如何配置 ExpressJS 渲染布局的路径

node.js - 如何在 mongodb 中的嵌入文档字段上使用 $lookup

mongodb - 添加节点 MongoDB 时 ReplicaSetId 冲突

express - Jade 变量插值 - 如果属性未定义,则为默认值?

node.js - Jade缓存模板和Node重启