Shu.T
Shu.T

Reputation: 479

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 => {
    return stundentNumber
  })

teacher
  .countDocuments
  (
    {}
  )
  .then(teacherNumber => {
    return teacherNumber;
  })

staff
  .countDocuments
  (
    {}
  )
  .then(staffNumber => {
    return staffNumber;
  });

Desired Response

res.json({
    teacher: teacherNumber,
    student: stundentNumber,
    staff: staffNumber
});

How can it be done using nodejs/mongoose

Upvotes: 2

Views: 913

Answers (2)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17925

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)})

Upvotes: 4

Richard Rublev
Richard Rublev

Reputation: 8162

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.

Upvotes: 0

Related Questions