【问题标题】:MongoDB get Value of a Field in NodeJSMongoDB在NodeJS中获取字段的值
【发布时间】:2020-07-16 15:34:45
【问题描述】:

我是 MongoDB 的新手,我尝试为与 NodeJS 的不和谐创建一个用户硬币系统。将新文档添加到集合中没有问题,但我不能只访问一个值。我想返回“硬币”的价值,让用户看到他的硬币。 我正在使用 find() 方法,它返回一个文档:

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

我尝试使用点访问“硬币”,但它总是返回未定义:

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);
    }
})

【问题讨论】:

  • Mongoose .find() 必须在 array[] 中为您提供结果,即使它只包含一个文档。您可能想尝试通过索引访问该值:res[0]['coins'] 等。
  • 就是这样!谢啦。我不知道 find() 返回数组。

标签: javascript node.js mongodb discord.js


【解决方案1】:
     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;

        })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 2016-06-29
    • 1970-01-01
    • 2019-03-12
    相关资源
    最近更新 更多