0

首先,我使用的是node.js、express.js、mongoose.js/mongodb。
我正在尝试按如下方式路由流量:

app.get('/:username/:language', pageRoutes.fetchLanguage);

当我处理以下查询时,我似乎得到了预期的结果(当我打印到 console.log 时,我看到了预期的输出)。但是,当我尝试以任何方式呈现页面时,都会出现错误。

var User = require('./../models/user-model');
var Language = require('./../models/language-model');
var Element = require('./../models/element-model');

exports.fetchLanguage = function(req, res) {
    var target_lang = req.params.language;

    // Find the user by username, so that I can get their _id
    User.findOne({username: req.params.username}, {_id: 1}, function(err, userdoc){

        // This prints the _id as expected
        console.log(userdoc._id); 

        // Find all languages associated with that user _id
        // (just need a list of language names)
        Language.find({_user_id: userdoc._id}, {name: 1}, function(err, languages){

            // Find the one language that was requested
            Language.findOne({_user_id: userdoc._id, name: target_lang}).populate('sections.elements').exec(function(err, languagedoc){

                // I can log the expected query results...
                console.log(JSON.stringify(languagedoc, undefined, 2));
                console.log(JSON.stringify(languages, undefined, 2));
                // But as soon as i try to render, things go wrong
                res.render('test', {languages: languages, language: languagedoc});
            });
        });
    });

这是错误:

Language.find({_user_id: userdoc._id}, {name: 1}, function(err, langua
                                    ^

TypeError: Cannot read property '_id' of null
at Promise.<anonymous>

该错误仅在我尝试呈现页面/发送响应时发生。我很困惑!我想我的问题是:为什么这个查询似乎处理正确,但也会产生错误?

4

1 回答 1

0

事实证明,我只需要删除查找操作的 _id

// This is correct
Language.find({_user_id: userdoc}, {name: 1}, function(err, languages) {
// NOT this
Language.find({_user_id: userdoc._id}, {name: 1}, function(err, languages) {
于 2014-03-14T07:03:34.547 回答