lau*_*kok 2 mongoose mongodb express
为什么 mongoose 在没有找到结果时总是返回 null 而不是错误?
Person.findOne({ 'name': 'Ghost' }, function (err, person) {
console.log(err); // null
if (err) return handleError(err);
});
Run Code Online (Sandbox Code Playgroud)
我的数据库中不存在“Ghost”这个人,所以我期待一个错误,但我得到的是 null。为什么?如何才能得到一个错误呢?
小智 5
因为mongoose只有在出现错误时才返回错误,所以没有找到任何结果并不是错误。如果返回 null,您可以处理响应,例如:
\n\nPerson.findOne({ 'name': 'Ghost' }, function (err, person) {\n if(person === null)\xc2\xa0{\n console.log('No results found');\n }\n if (err) return handleError(err);\n});\nRun Code Online (Sandbox Code Playgroud)\n\n或者
\n\nPerson.findOne({ 'name': 'Ghost' }, function (err, person) { \n if (err) {\n return handleError(err);\n } else if (person) {\n return person;\n } else {\n return 'No results found';\n \xc2\xa0}\n});\nRun Code Online (Sandbox Code Playgroud)\n