0

我将 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 存在它应该从数据库中获取它的内容(这实际上有效)。这是我现在输入不正确的 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)
4

2 回答 2

1

对于不存在的 ID 不返回任何数据是正常操作,而不是错误,因此没有设置 err。

尝试更改if (!err)if (!err && user_).

于 2011-05-30T14:51:49.120 回答
-1

尝试切换回调参数 >

User.findById(user_id, function(user_, err ) {
    if (!err) {
        res.render('track', { pins: user_.pins, layout: false });
    } else {
        res.send("FAIL! " + err);
    }
});
于 2011-05-30T09:15:38.043 回答