我使用express.js和mongoose进行mongoDB访问。如果有人输入不存在的URL(基于user_id),我会尝试实现回退。这是代码:
app.get('/track/:id', function(req, res) {
var user_id = req.params.id;
User.findById(user_id, function(err, user_) {
if (!err) {
res.render('track', { pins: user_.pins, layout: false });
} else {
res.send("FAIL! " + err);
}
});
});
当访问http://foo.bar/track/1234并且1234不存在时,它应该打印出FAIL !,如果id存在,它应该从db获取它的内容(这实际上有效)。输入错误的ID(应用程序崩溃)时,这就是我现在得到的结果:
/home/node/node-service/releases/20110530081158/server.js:112
res.render('track', { pins: user_.pins, layout: false });
^
TypeError: Cannot read property 'pins' of null
at /home/node/node-service/releases/20110530081158/server.js:112:46
at /home/node/.node_libraries/.npm/mongoose/1.3.6/package/lib/mongoose/query.js:778:22
at [object Object].<anonymous> (/home/node/.node_libraries/.npm/mongoose/1.3.6/package/support/node-mongodb-native/lib/mongodb/collection.js:462:35)
at [object Object].emit (events.js:67:17)
at [object Object].<anonymous> (/home/node/.node_libraries/.npm/mongoose/1.3.6/package/support/node-mongodb-native/lib/mongodb/db.js:94:12)
at [object Object].emit (events.js:64:17)
at Socket.<anonymous> (/home/node/.node_libraries/.npm/mongoose/1.3.6/package/support/node-mongodb-native/lib/mongodb/connection.js:86:16)
at Socket.emit (events.js:64:17)
at Socket._onReadable (net.js:671:31)
at IOWatcher.onReadable [as callback] (net.js:177:10)
答案 0 :(得分:1)
不返回不存在的ID的数据是正常操作,而不是错误,因此没有设置错误。
尝试将if (!err)
更改为if (!err && user_)
。
答案 1 :(得分:-1)
尝试切换回调参数&gt;
User.findById(user_id, function(user_, err ) {
if (!err) {
res.render('track', { pins: user_.pins, layout: false });
} else {
res.send("FAIL! " + err);
}
});