-1

while retrieving image name from my database, i am able to retrieve full object, but i just want the specific value.

Example while running the following code:

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

when I log the image name, after else above I get following output

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

While I just want to extract the value of the image that is (image-1589817207200.PNG' || image-1589817409060.PNG' || imagename: 'image-1589817473811.jpeg').

I spent days searching online,and i got many answers including one on StackOverflow,that said use Object.keys(imagename),but that just logged index number ( [ '0', '1', '2' ] ) which I don't want. I just want the specific image name.

Thanks in advance

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
Riyazat Durrani
  • 588
  • 1
  • 8
  • 20
  • Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) As given over there you can get just wanted element from DB, rather than getting everything & finding for needed element in array using code ! – whoami - fakeFaceTrueSoul May 18 '20 at 16:46
  • thanks alot for this,i tried this way before,but couldn't get the answer. below @max has done it correctly. – Riyazat Durrani May 18 '20 at 17:19

2 Answers2

1

you can map your response:

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

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

console.log(result)
max
  • 469
  • 3
  • 10
1

Sadly, I cannot comment, but as far as I understand you want to get the value from each image object in the array and compare them (?).

You can just iterate over it and get each imagename value like this:

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

You can also select with a where clause directly via mongoose (consult https://mongoosejs.com/docs/api.html#model_Model.find for more)

Timon
  • 359
  • 3
  • 10