Generate an array from a query in mongoDB (Mongoose)

0

Good morning! I need the data from a mongo collection on the front end.

I'm using Mongoose as an ODM, and I was a little lost in sending the data to the front end.

In the query it returns me the documents in the collection, and then I need them in JSON (I believe) to use them in the front end to generate a graphic.

This is the route I'm using

router.get('/home', isAuthenticated, function(req, res){

    atendimentos.find({}, async function(err, atendimentos) {
         if(!err){
              console.log(atendimentos);
         }
    })

    res.render('home', {user: req.user, atendimentos: atendimentos});
})

I saw that I could use lean (), but it returns pure javascript objects from what I understand. I could use it and use a JSON.stringify I imagine, but there on the route I can not use two res, if not crash application.

I would like to know how I could do to have this data on the front end, if anyone can give me a light, thank you very much!

    
asked by anonymous 01.08.2018 / 14:09

1 answer

0

To pass the data and receive on the front.

router.get('/home', isAuthenticated, function(req, res){
    atendimento.find({}, (err, result) => {
        if(!err){
            res.render('home', { result })
        }else{
            console.log(err)
        }            
})

And I use ejs as a view engine there to have access to the data is very simple only using this syntax <% = atendimento.name %> or <%= user %>

  

Async / await

router.get('/home', isAuthenticated, async (req, res) =>{
    const result = await atendimento.find({})
    res.render('home', { result })           
})
    
01.08.2018 / 17:53