我有一个带有用户对象的 mongob。这是架构:
{
"_id": {
"$oid": "50658c835b821298d3000001"
},
"email": "admin",
"password": "admin",
"id": 1
}
我写了一个简单的演示(只有主要部分):
function findByEmail(email, callback) {
db.collection("users", function(err, collection) {
collection.find({}, function(err, users) {
users.each(function(err, user) {
if (user) {
if (user.email === email) {
//for a case, is we found user - return it
callback(null, user);
}
}
});
//for a case, is we didn't find user - return null
callback(null, null);
});
});
}
以及测试路线:
app.get('/test',function(req,res){
findByEmail("admin", function(err, user){
res.send(user);
})
})
启动 localhost:3000/test 后,我得到
Error: Can't set headers after they are sent.
如果我评论行callback(null, null);
,我不会收到此错误。似乎回调有效......两次!怎么会这样?我想如果我if (user.email === email) { ... }
工作并callback(null, user);
启动,函数findbyEmail
返回<user>
到app.get
,但回调工作两次(callback(null, null);
也),即使if (user.email === email) { ... }
是真的。