Skip to content Skip to sidebar Skip to footer

How To Get A Multiple Result In Mongoose And Combine It In One Single Response

In a API(Route) call, I wish to have 3 mongoose query and then combine results to form a response json. Query student .countDocuments ( {} ) .then(stundentNumber =>

Solution 1:

If you're using async-await's then try as like below where Promise.all() will help you to execute all operations in parallel :

async function getCounts() {
    let [student,teacher,staff] = await Promise.all([student.countDocuments({}),teacher.countDocuments({}),staff.countDocuments({})]);
    return {student,teacher,staff};
}

/** call this function in main handler function where you get API call */
getCounts().then((data)=>{res.json(data)}).catch((err)=>{console.log(err)})

Solution 2:

You must build student,teacher and staff model

const mongoose = require("mongoose"),
{Schema} = mongoose,
  studentSchema = new Schema(
    {
      name: {
        first: {
          type: String,
          trim: true
        },
        last: {
          type: String,
          trim: true
        }
      },
      studentNumber: {
        type: Number,
        required: true,
        lowercase: true,
        unique: true
      },
    }

Same model for the other two. After that,you must write function query. Read more about queries.


Post a Comment for "How To Get A Multiple Result In Mongoose And Combine It In One Single Response"