【发布时间】: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'])这是我不想要的。 我只想要具体的图片名称。
提前致谢
【问题讨论】:
-
这能回答你的问题吗? Retrieve only the queried element in an object array in MongoDB collection 正如那里给出的那样,您可以从 DB 中获取所需的元素,而不是使用代码获取所有内容并在数组中查找所需的元素!
-
非常感谢,我以前尝试过这种方式,但无法得到答案。低于@max 已正确完成。
标签: node.js database mongodb mongoose