Mongoose查询返回未定义的结果

时间:2018-04-11 02:30:23

标签: javascript node.js mongodb express mongoose

我有这个对象

{
    websites: ['georgiancollege.ca'],
    keys:
        [{
            _id: 5ac529fe51811331a3b824e5,
            name: 'Google',
            value: 'key_example'
        },
            {_id: 5ac529fe51811331a3b824e4, name: 'Facebook', value: ''},
            {_id: 5ac529fe51811331a3b824e3, name: 'Instagram', value: ''}],
    _id: 5ac529fe51811331a3b824e2,
    username: 'a@a.a',
    isPremium: false,
    __v: 0
}

这段代码:

router.get('/keys/edit/:user_id&:key_id', (req, res, next) => {
    Account.findOne({_id: req.params.user_id}, (err, acc) => {
        console.log(acc);
        console.log();
        var selectedKey = findById(acc.keys, req.params.key_id);
        console.log(selectedKey);
        res.render('admin/edit', {
            title: 'Edit keys',
            user: req.user,
            key: selectedKey,
            account: acc,
        });
    });
});

这是findById()方法:

function findById(source, id) {
    return source.filter((obj) => {
        // coerce both obj.id and id to numbers
        // for val & type comparison
        return obj.id === id;
    })[0];
}

我想要实现的是将api-key传递给视图。问题是selectedKey查询返回undefined。为什么?这似乎有道理。

通过params传递的密钥是正确的。

2 个答案:

答案 0 :(得分:2)

router.get('/keys/edit/:user_id&:key_id', (req, res, next) => {
    Account.findOne({_id: req.params.user_id}, (err, acc) => {
        console.log(acc);
        console.log();
        var selectedKey = findById(acc.keys, req.params.key_id);

        if(selectedKey){
            console.log(selectedKey);
            res.render('admin/edit', {
                title: 'Edit keys',
                user: req.user,
                key: selectedKey,
                account: acc,
            });'
        } else {
            // Add your code if selectedKey is not exist
        }
    });
});

function findById(sources, id) {
    if(!sources) return null;

    let source= sources.find(_s=>{
         return _s._id.toString() === id;
    })
    // If you need only value
    return source ? source.value : null;

    // Else
    // return source ? source : null;
}

希望这会帮助你...

答案 1 :(得分:1)

    router.get('/keys/edit/:user_id&:key_id', (req, res, next) => {
        Account.findOne({ _id: req.params.user_id }, (err, acc) => {
            console.log(acc);
            console.log();
            findById(acc.keys, req.params.key_id)
                .then(selectedKey => {
                    console.log(selectedKey);
                    res.render('admin/edit', {
                        title: 'Edit keys',
                        user: req.user,
                        key: selectedKey,
                        account: acc,
                    });
                });
        });
    });

    findById(){
       return new Promise((resolve, reject)=>{
           // ... your code here 
          resolve('your key');
       })
    }
  在findById()方法之前呈现的

文件返回'selectedKey'   所以在解决之后使用诺言。渲染你的页面。