3

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);
    }
})
2
  • 1
    Mongoose .find() must be giving you results in an array[] even though it contains only one document. You might want to try accessing the value via index: res[0]['coins'] etc. Commented Apr 4, 2020 at 15:31
  • 1
    That's it! Thanks man. I didn't know find() returns arrays. Commented Apr 4, 2020 at 15:41

1 Answer 1

2
     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;

        })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.