MongoDB get Value of a Field in NodeJS

Viewed 861

I'm new to MongoDB and I try to create a User Coin System for discord with NodeJS. There is no problem in adding new documents to the collection but i can not access only a single value. I want to return the value of "coins" to let the user see his coins. I'm using the find() method and it returns a document:

    {
    "_id": {
        "$oid": "5f875963b622f72c3850da6f"
    },
    "username": "Test",
    "userID": "1234",
    "messages": {
        "$numberInt": "22"
    },
    "coins": {
        "$numberInt": "210"
    },
    "__v": {
        "$numberInt": "0"
    }
}

I tried to access "coins" with dot but it always returns undefined:

User.find({userID: message.author.id}).exec((err, res) => {
  if (err) return console.log(err);

  let embed = new Discord.RichEmbed()
    .setTitle(message.author.tag)
    .setColor("#4000FF")
    .setThumbnail(message.author.displayUserAvatarURL);
//User has no Coins
    if(!res){
      embed.addField("Coins", "0", true);
      return message.reply(embed);
    }else {
//res.coins are undefined. Returning 'res' is the whole document from above.
      embed.addField("Coins", res.coins , true);
      return message.reply(embed);
    }
})
1 Answers
     1. Try using findOne 
2. check  your userId  in db is string format so it could be a problem .
3. Convert your  message.author.id to string before finding. then you will find everything in your result object


    let user_id=message.author.id;
        User.findOne({userID: user_id.toString()},function(error, body) {
                                   if (error){
                                    result(error, null);
                                   }
         var  results= body;

        })
Related