How to overwrite one field of a schema with another in mongodb

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

2 answers

  • answered 2021-10-24 18:09 Sahil Jain

    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();
    });
    

  • answered 2021-10-25 05:59 turivishal

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum