我有这个对象
{
websites: ['georgiancollege.ca'],
keys:
[{
_id: 5ac529fe51811331a3b824e5,
name: 'Google',
value: 'key_example'
},
{_id: 5ac529fe51811331a3b824e4, name: 'Facebook', value: ''},
{_id: 5ac529fe51811331a3b824e3, name: 'Instagram', value: ''}],
_id: 5ac529fe51811331a3b824e2,
username: '[email protected]',
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键传递给视图。问题是
selectedKey
查询返回未定义。为什么?这似乎是有道理的。用
params
传递的密钥是正确的。 最佳答案
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;
}
希望这可以帮助您...