mongo/node TypeError: callback is not a function on query

a 夏天 提交于 2019-12-24 15:42:58

问题


I am trying to determine if a document exists in a collection. If the document exists, I wish to add a property "unread = false" to an object. If it does not exist, I wish to insert the document and add "unread = true" to the object.

Code in coffee script for the above is as follows:

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

The error I am receiving is

/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

Can someone explain to me the reason this error is occurring and what a potential solution might be?


回答1:


The MongoDB Native Driver for Node follows the Node.js convention for async functions, namely that each method receives a callback function as the last parameter. So instead of db.collection.find(query).count(), your function should be rewritten as:

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

The parameter count captures your query's result.

You could also simplify the function to db.collection.count(query, function(err, count){}.

Your insert function should also follow the same convention, using a callback function with form of function(err, res){} as the last parameter.

I'd recommend looking at the MongoDB Native Driver Docs for more information.

Edited to give example in CoffeeScript: Here's the function rewritten with CoffeeScript syntax.

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


来源:https://stackoverflow.com/questions/34966349/mongo-node-typeerror-callback-is-not-a-function-on-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!