Home > front end >  How to overwrite one field of a schema with another in mongodb
How to overwrite one field of a schema with another in mongodb

Time:10-25

how can I overwrite the value of officialLyric with the value of updateLyric??

artist: { type: String, required: true },
title: { type: String, required: true },
officialLyric: { type: String, required: true },
editedLyrics: [
  {
    updatedLyric: String,
    status: {
      type: String,
      enum: ["Aproved", "Rejected", "Pending"],
      default: "Pending",
    },
    userId: { type: Schema.Types.ObjectId, required: true, ref: "User" },
  },
],
releaseDate: { type: Date },

see image for clear depiction of the question.

enter image description here

CodePudding user response:

If you want to always have to value of latest updateLyric in editedLyric array in officialLyric, you don't need to actually store officialLyric in DB. you can use mongoose virtual fields and remove officialLyric from schema.

LyricSchema.virtual('officialLyric').get(function () { 
    if(!this.editedLyrics.length) return null;
    return this.editedLyrics[this.editedLyrics.length-1].updatedLyric;
});

If you still want to store the officialLyric first and then overwrite it with edited version you save. You can use hooks.

LyricSchema.post('save', async(error, doc, next) => {
    if(doc.editedLyrics.length && doc.officialLyric != doc.editedLyrics[doc.editedLyrics.length-1].updatedLyric){
        doc.officialLyric = doc.editedLyrics[doc.editedLyrics.length-1].updatedLyric;
        await doc.save();
    }
    next();
});

CodePudding user response:

You can try update with aggregation pipeline starting from MongoDB 4.2,

  • $arrayElemAt to get first value of updatedLyric from editedLyrics array and update it into officialLyric
db.collection.updateMany(
  {}, // put your query
  [{
    $set: {
      officialLyric: {
        $arrayElemAt: ["$editedLyrics.updatedLyric", 0]
      }
    }
  }]
)

Playground

  • Related