Home > Software design >  Nested Schema in Mongoose with NestJS
Nested Schema in Mongoose with NestJS

Time:08-05

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:

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?

CodePudding user response:

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.

  • Related