[英]Mongoose query returns undefined result
I have this object 我有这个对象
{
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
}
And this code: 这段代码:
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,
});
});
});
This is the findById() method: 这是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];
}
What I'm trying to achieve is pass the api-key to the view. 我想要实现的是将api键传递给视图。 The problem is that the selectedKey
query returns undefined. 问题是selectedKey
查询返回未定义。 Why? 为什么? It seems to make sense. 这似乎是有道理的。
The keys passed with params
are correct. 用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;
}
Hope this will help you out... 希望这可以帮助您...
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');
})
}
file rendered before findById() method return 'selectedKey'. 在findById()方法之前呈现的文件返回'selectedKey'。
so use promise after it resolved. 所以解决后要使用promise。 render your page. 呈现您的页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.