kok sopanha
kok sopanha

Reputation: 21

How to return count array of subdocuments mongoose

I want to get the total amount of comments from Place models and I couldn't find a way to get it because I don't want to populate the comment with GET /places.

This is my place model

 const placeSchema = mongoose.Schema(
  {
    type: { type: String },
    english: { type: String },
    province_code: { type: String },
    district_code: { type: String, required: true },
    commune_code: { type: String },
    village_code: { type: String },
    lat: { type: Number },
    lon: { type: Number },
    body: { type: String },
    images: [{ type: String }],
    comments: [{ type: mongoose.Types.ObjectId, ref: Comment }],
  },
  {
    timestamps: {
      createdAt: 'created_at',
      updatedAt: 'updated_at',
    },
  }
)

I use this query

data = await Place
          .find()
          .limit(5)
          .skip(0)
          .populate('comments')
          .exec()

I want to get the response like this

 {
    "data": [
        {
            "images": [],
            "comments": 6,
            "type": "place",
            "english": "99Boko",
            "province_code": "23",
            "district_code": "2302",
            "commune_code": "230202",
            "village_code": "23020202",
            "lat": 135.2039,
            "lon": 104.01734762756038,
            "body": "<b>This place is really good</b>",
            "created_at": "2021-07-20T17:41:52.202Z",
            "updated_at": "2021-07-20T17:41:52.202Z",
            "id": "60f70ae08e54941530d14c4c"
        },
]}

Does anybody know the solution to get this kind of response ?

Upvotes: 1

Views: 115

Answers (1)

kok sopanha
kok sopanha

Reputation: 21

I have figured out to get the comment length is to use virtual count

placeSchema.virtual('comment_length', {
  ref: Comment, // model to use for matching
  localField: 'comments', // from `localField` i.e., Place
  foreignField: '_id', // is equal to `foreignField` of Comment schema
  count: true, //only get the number of docs
})

placeSchema.set('toObject', { virtuals: true })
placeSchema.set('toJSON', { virtuals: true })

and use this query

 data = await Place
            .find().populate({ path: 'comment_length', count: true })
            .exec()

Upvotes: 1

Related Questions