0

Here is my schema:

const mongoose = require("mongoose");
const {ObjectID} = mongoose.Schema.Types;

const productSchema = mongoose.Schema({
  productUUID:{type: String, required: true, trim: true},
  submittedDate: {type: Date, default:"1900-01-01"},
  productStatus:{type: String, default:"Open", trim: true},
  productEvaluationSectionA:[{
    question1:{type: String,default:"How good is product A?", trim: true},
    AQ1:{type: Number},
    question2:{type: String,default:"How good is product B?", trim: true},
    AQ2:{type: Number},
    question3:{type: String,default:"How good is product C?", trim: true},
    AQ3:{type: Number},
  }],
  productEvaluationSectionB:[{
    question1:{type: String,default:"Is product color blue good?", trim: true},
    BQ1:{type: Number},
    question2:{type: String,default:"Is product color red good?", trim: true},
    BQ2:{type: Number},
    question3:{type: String,default:"Is product color green good?", trim: true},
    BQ3:{type: Number},
    question4:{type: String,default:"Is product color yellow good?", trim: true},
    BQ4:{type: Number},
    question5:{type: String,default:"What color do you prefer?", trim: true},
    BQ5:{type: String, trim: true},
  }],
},{timestamps: true });

When I did a console.log(req.body) I get this result:

sectionAData: { AQ1: '5', AQ2: '5', AQ3: '5' },
sectionBData: { BQ1: '5', BQ2: '5', BQ3: '5', BQ4: '5', BQ5: '' }

Now I try to destructure it:

const { AQ1, AQ2, AQ3 } = req.body.sectionAData
const { BQ1, BQ2, BQ3, BQ4, BQ5 } = req.body.sectionBData

After destructuring it, I try to findOneAndUpdate.

 await Product.findOneAndUpdate({ productUUID: { "$eq": "8fda98ad-fdfd-4f65-a4b8-05d7dabd796c" }, productStatus: { "$eq": "Open" }},
      {
        $set: {          
          "submittedDate": moment().format('YYYY-MM-DD, hh:mm:ss a'),
          "productStatus":"Closed",
          "productEvaluationSectionA.AQ1": AQ1,
          "productEvaluationSectionA.AQ2": AQ2,
          "productEvaluationSectionA.AQ3": AQ3,
          "productEvaluationSectionB.BQ1": BQ1,
          "productEvaluationSectionB.BQ2": BQ2,
          "productEvaluationSectionB.BQ3": BQ3,
          "productEvaluationSectionB.BQ4": BQ4,
          "productEvaluationSectionB.BQ5": BQ5,
        }}, { upsert:true },
    )

I get an error in the findOneAndUpdate:

MongoServerError: Cannot create field 'AQ1' in element {productEvaluationSectionA: []}

Where did I get it wrong here? Thanks

LNW LNW
  • 55
  • 1
  • 8
  • check this answer https://stackoverflow.com/questions/15691224/mongoose-update-values-in-array-of-objects – salman Feb 28 '22 at 16:15

0 Answers0