Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested Schema in Mongoose with NestJS

I am trying to parse a response from Google’s API into Mongoose using Nestjs, but I can’t understand what is the correct way to parse and create a Schema for nested json objects, can someone help?

This is my JSON response:

{
  "reviewId": "f1a0ec26-9aca-424f-8b05-cff6aa3d2337",
  "authorName": "Some User",
  "comments": [
    {
      "userComment": {
        "text": "\tAmazing!",
        "lastModified": {
          "seconds": "1659685904",
        },
        "starRating": 5,
        "reviewerLanguage": "en",
      }
    },
    {
      "developerComment": {
        "text": "Thank you.",
        "lastModified": {
          "seconds": "1659688852",
        }
      }
    }
  ]
}

This is my Scheme:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import * as mongoose from 'mongoose';

export interface Review extends mongoose.Document {
  authorName: string;
  reviewId: string;
  userComment: {
    text: string;
    lastModified: string;
    starRating: number;
    reviewerLanguage: string;
  };
}

export const ReviewSchema = new mongoose.Schema({
  authorName: { type: String, required: true },
  reviewId: { type: String, index: { unique: true }, required: true },
  userComment: {
    text: { type: String, required: false },
    lastModified: { type: String, required: false },
    starRating: { type: Number, required: false },
    reviewerLanguage: { type: String, required: false },
  },
});

Then I am trying to create the object when the JSON response returned from the server:

const newReview = new this.reviewModel({
  authorName: review.authorName || 'NO_NAME',
  reviewId: review.reviewId || 'NO_ID',
  userComment.lastModified: review.userComment[0].lastModified || '',
});

enter image description here

enter image description here

But I get an error in userComment.lastModified, what is the correct way to do it?

>Solution :

The method is quite wrong, as the objects given in Models are key:value you cannot do

userComment.lastmodifird:"abc"

const newReview = new this.reviewModel({
   authorName: review.authorName || 'NO_NAME',
   reviewId: review.reviewId || 'NO_ID',
   userComment:{lastModified: review.userComment[0].lastModified || ''},
   });

Let me know if it does not work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading