Search code examples
mongoosefindchaining

Mongoose Model.FindOne and Model.Find with one query


I'm doing a project for training. And I have this route

('/news/:category/:title', (req, res) 

Here I want to pick up one particular article (I'm querying database by title - it's unique) which is in

 req.params.title

and the rest articles f.e 15 items. How can I do that? Can I chain findOne and find somehow and render it in one view?


Solution

  • Here's how you can do it with Promise.all:

    var findOne = Article.findOne({title: req.params.title});
    var findAll = Article.find({});
    
    Promise.all([findOne, findAll]).then(articles => { 
      console.log(articles); // articles[0] contains findOne result, articles[1] findAll
    }, reason => {
      console.log(reason)    // if one of the promises rejected
    });