Problem capturing object value

Asked

Viewed 31 times

-1

I’m doing a database search (mongoDB) so it returns me an array, I just wanted to be picking up an array object but I’m not getting it.

app.get("/", (req, res)=>{
        Gift.find().lean().then(gifts =>{
            res.render("loja/index", {gifts: gifts})
            console.log(gifts._id)
        })
    })

I was able to capture that value using just findOne, in this case, what exactly I would have to be doing so I could be capturing all the _id of my documents?

1 answer

0

To obtain the _id of your data just do the search using the .find() or distinct. There are different ways to return the information as you would like beyond the ones I am quoting, because the _id already comes by default in all queries we make in Mongodb.

For this case I recommend the use of distinct in this way:

app.get("/", (req, res)=>{
    Gift.distinct('_id', {}).lean().then(gifts =>{
      res.render("loja/index", {gifts: gifts})
      console.log(gifts)
    })
})

Or using Async/Await

app.get('/', (req, res) => {
  try{
    const gifts = await Gifts.distinct('_id', {})
    return res.render('/loja/index', { gifts })
  } catch(err) {
    console.log(err)
  }
})
  • I understood, in the case, from what I understood the distinct returns distinct values from fields, i.e., Gifts. _id was an example, but if I wanted to be taking the value of Gifts.value to so perform a sum of such, this would not fit, because it can contain several objects with the same value, so I understood that would be basically what occurs, correct me if I’m wrong on this issue.

  • Yes, it will bring only the selected fields, as far as I could see it was what you wanted. Take a look at these answers link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.