我在MongoDB上使用Mongoose,我发现了这个问题。我在数据库中找到一个对象,然后我只返回对象属性,但是当我调用变量时,它返回整个对象而不是想要的属性。
var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag}, function(err, user){
if (err) {
console.log(err);
} else {
return user.characters
}
})
console.log(CharacterInDbCounter);
返回:
{ _id: 5a25a14a05656b24accfe231,
id: 1234,
battletag: 'Something',
provider: 'bnet',
__v: 0,
characters:
[ 5a25a14a05656b24accfe218,
5a25a14a05656b24accfe219,
5a25a14a05656b24accfe21a,
5a25a14a05656b24accfe21b,
5a25a14a05656b24accfe21c,
5a25a14a05656b24accfe21d,
5a25a14a05656b24accfe21e,
5a25a14a05656b24accfe21f,
5a25a14a05656b24accfe220,
5a25a14a05656b24accfe221,
5a25a14a05656b24accfe222,
5a25a14a05656b24accfe223,
5a25a14a05656b24accfe224,
5a25a14a05656b24accfe225,
5a25a14a05656b24accfe226,
5a25a14a05656b24accfe227,
5a25a14a05656b24accfe228,
5a25a14a05656b24accfe229,
5a25a14a05656b24accfe22a,
5a25a14a05656b24accfe22b,
5a25a14a05656b24accfe22c,
5a25a14a05656b24accfe22d,
5a25a14a05656b24accfe22e,
5a25a14a05656b24accfe22f ] }
答案 0 :(得分:1)
为了实现目标,您必须以promise方式
执行此操作var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
.then(function(user){
return user.characters
})
console.log(CharacterInDbCounter);
不幸的是,当您使用await
时,您无法catch
承诺错误catch
,您必须在try/catch
中包围您的代码以捕获异常并在then
内查看如果user
参数未定义或为空
try {
var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
.then(function(user) {
if (!user) {
// user not found
}
return user.characters
})
console.log(CharacterInDbCounter);
} catch(e) {
// catch unexpected errors
}