【问题标题】:how do i get the key value instead of full object in mongoDB (node.js)我如何在mongoDB(node.js)中获取键值而不是完整对象
【发布时间】:2025-12-24 18:35:07
【问题描述】:

在从我的数据库中检索图像名称时,我可以检索完整的对象,但我只想要特定的值。

运行以下代码时的示例:

app.get("/data", function (req, res) {
  if (req.isAuthenticated()) {

    User.findById(req.user.id, function (err, foundUser) {

    Comment.find({userId:foundUser.id},{_id:0,imagename:1} ,function(err,imagename){
      if(err){
        console.log(error);
      }
      else{
        console.log(imagename);

        res.render("data", { EJS: a });
      }
    })
  })
  } else {
    res.redirect("/firstpage");
  }
});

当我记录图像名称时,在上面的 else 之后我得到以下输出

[ 
  { imagename: 'image:image-1589817207200.PNG' },
  { imagename: 'image-1589817409060.PNG' },
  { imagename: 'image-1589817473811.jpeg' }
]

虽然我只想提取图像的值,即 (image-1589817207200.PNG' || image-1589817409060.PNG' || imagename: 'image-1589817473811.jpeg')。

我花了几天的时间在网上搜索,我得到了很多答案,包括 * 上的一个,说使用 Object.keys(imagename),但只是记录了索引号(['0','1','2'])这是我不想要的。 我只想要具体的图片名称。

提前致谢

【问题讨论】:

标签: node.js database mongodb mongoose


【解决方案1】:

您可以映射您的响应:

arr = [ 
    { imagename: 'image:image-1589817207200.PNG' },
    { imagename: 'image-1589817409060.PNG' },
    { imagename: 'image-1589817473811.jpeg' }
  ];

let result = arr.map(img => img.imagename);

console.log(result)

【讨论】:

  • 是的,得到了​​答案,非常感谢。非常感激。如果你能详细说明 arr.map(img => img.imagename);对我来说行,因为我是编程新手。
  • 抱歉弄错了。在您发表评论后才注意到。应用
【解决方案2】:

遗憾的是,我无法发表评论,但据我了解,您希望从数组中的每个图像对象中获取值并比较它们 (?)。

您可以迭代它并像这样获取每个图像名称值:

 imagename.forEach(imageObj => {
  if (imageObj.imagename === 'your value') {
    // your logic
  }
});

您也可以直接通过 mongoose 使用 where 子句进行选择(更多信息请咨询 https://mongoosejs.com/docs/api.html#model_Model.find

【讨论】:

  • @max 很可能理解正确,所以你几乎可以忽略我的回答 :)
  • 非常感谢您抽出宝贵时间,虽然这不是我想要的,但@max 确实得到了正确的答案。非常感谢。