Tuesday, 4 April 2017

Returning the results of a Mongoose/MongoDB query [duplicate]

I have a Node.js app and am using MongoDB/Mongoose. I think that my problem might be my fuzzy understanding of promises, and how Mongoose uses them. I am not able to push the results of the Mongoose query to a list.

docList is a list of document ids.

I want to do the following:

  • Create an array idNameList, which will contain ids and titles of Doc objects.
  • To do this I want to run a for loop matching docList ids to titles and pushing them to the idNameList array.
  • Render a template, pushing the array idNameList to the template.

Here is what I have.

router.get('/', function(req, res) {
    let idNameList = []
    for(let item of docList)
    {
        let pushTitle = ""
        Doc.findById(item, "title", function(err, doc) {
            if (err) res.send(err)
                pushTitle = doc.title
                idNameList.push( { "id": item, "name" : pushTitle } )
            }
    }
    res.render('index', { idNameList: idNameList })
}

This currently sends a blank array, [], to the template. If I put a console.log(idNameList) in the query, it is returning the correct ids and names. How can I fix this so that the queries in the for loop are returned in the array?



via Nathan

No comments:

Post a Comment