kokoto13
kokoto13

Reputation: 67

Mongoose find return only exact property from object

I am using Mongoose with MongoDB and i have found this problem. I find one object in database, then i return only the object property, but when i call the variable it returns whole object not the wanted property.

var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag}, function(err, user){
    if (err) {
        console.log(err);
    } else {
        return user.characters
    }
})
console.log(CharacterInDbCounter);

returns:

{ _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 ] }

Upvotes: 2

Views: 2225

Answers (1)

Farnabaz
Farnabaz

Reputation: 4066

In order to achieve your goal you must do it in promise way

var CharacterInDbCounter = await UserModel.findOne({battletag: req.user.battletag})
    .then(function(user){
        return user.characters
    })
console.log(CharacterInDbCounter);

Unfortunately when you use await you cannot catch errors by promise catch, you must surround your code in try/catch to catch exception and inside then check if user argument is not undefined or empty

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
}

Upvotes: 1

Related Questions