0

I'm getting a json with this structure:

"quality": [
                {
                    "cod": "000000",
                    "month": "09/2021",
                    "average": [
                        {
                            "status": "0",
                            "type": "....",
                        },
                        {
                            "status": "0",
                            "type": "....",
                        },
                    ]
                },
                {
                    "cod": "0000123",
                    "month": "10/2021",
                    "average": [
                        {
                            "status: "0",
                            "type": "....",
                        },
                        {
                            "status: "0",
                            "type": "....",
                        },
                    ]
                },

I can access this array with this line of code:

response.data.data[0].quality[0].average

I'm declaring the model like this:

var averageSchema = new mongoose.Schema({
  status: String,
  type: String,
  
});
.
.
average: [{averageSchema}],

I can manipulate and access each one and save, but I can't all. I can save separately like this:

const Datas = db.dados_produtivos;
.
.

status = response.data.data[0].quality[0].average[0].status
type = response.data.data[0].quality[0].average[0].type

const data = new Data({
    .
    .
    quality: [{
        "cod": cod,
        "month": month,
        average: [{
            status: status,
            type: type,
        }],
    }],

.
.
.
    await data.save();

                       

How can I save everything at once? I tried to loop to save the data, but I couldn't manipulate it.

I followed this link to make the loop, but to no avail:

I appreciate if anyone can help me analyze.

E. Biagi
  • 452
  • 3
  • 12

1 Answers1

0

you can construct an average array by mapping response data to averageSchema data, then set it as stored value

const Datas = db.dados_produtivos;
.
.
averages = response.data.data[0].quality[0].average.map(a => ({ status: a.status, type: a.type }))

const data = new Data({
    .
    .
    quality: [{
        "cod": cod,
        "month": month,
        average: averages,
    }],

.
.
.
    await data.save();
SorosLiu
  • 111
  • 1
  • 1
  • 7