Node.js 正在find.exec()中执行两次回调
因此,我有以下代码:Node.js 正在find.exec()中执行两次回调,node.js,mongoose,Node.js,Mongoose,因此,我有以下代码: api.find = function(filter, sort, skip, limit){ var callback = typeof arguments[arguments.length - 1] === 'function'? arguments[arguments.length - 1] : function(){}; University.model.find(filter).sort(sort).skip(skip).limit(limit)
api.find = function(filter, sort, skip, limit){
var callback = typeof arguments[arguments.length - 1] === 'function'? arguments[arguments.length - 1] : function(){};
University.model.find(filter).sort(sort).skip(skip).limit(limit).exec(function(err, universities){
console.log('callbacking api.find');
callback(err, universities);
})
};
及
及
当我加载/删除时,我得到错误信息:
Error: Can't set headers after they are sent.
api.find中的console.log执行一次,controller.index中的console.log执行两次
我没有其他地方可以调用index方法,所以我真的不明白这一点。您已经调用了
api。使用回调作为第一个参数查找。我在api的第一行中看到了。查找
从哪里得到这个回调,但是请注意,filter==callback
。然后将筛选器传递给University.model.find
,并在exec
的回调中调用它University.model.find
将其最后一个参数解释为回调(如果它是函数),因此从该参数调用一次,从回调到exec
调用一次
在解析参数时需要更加小心;如果要将某个内容解释为回调,请不要将其用作其他内容。尝试在渲染后添加res.end()
app.get('/universities/', controller.index);
Error: Can't set headers after they are sent.