简体   繁体   English

express.js + mongoose:回退到不正确的 ID?

[英]express.js + mongoose: Fallback on incorrect ID?

i use express.js with mongoose for mongoDB access.我将 express.js 与 mongoose 一起用于 mongoDB 访问。 i try to implement a fallback, if someone enters an url which does not exist (based on the user_id).如果有人输入不存在的 url(基于 user_id),我尝试实施后备。 here's the code:这是代码:

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);
    }
});
});

when accessing http://foo.bar/track/1234 and 1234 doesn't exist, it should print out FAIL,.当访问http://foo.bar/track/1234并且 1234 不存在时,它应该打印出 FAIL,。 if the id exist it should get it's content from the db (this actually works): this is what i get now when entering an incorrect id (the app crashes):如果 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)

Returning no data for an ID that doesn't exist is normal operation, not an error, and so err is not being set.对于不存在的 ID 不返回任何数据是正常操作,而不是错误,因此没有设置 err。

Try changing if (!err) to if (!err && user_) .尝试将if (!err)更改为if (!err && user_)

try switching the callback params >尝试切换回调参数 >

User.findById(user_id, function(user_, err ) {
    if (!err) {
        res.render('track', { pins: user_.pins, layout: false });
    } else {
        res.send("FAIL! " + err);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM