Search code examples
node.jsmongodbmongoosemigration

How to change a MongoDB schema property on production


How can I easily change MongoDB documents on a production database? Having a small downtime is not a dealbreaker for me.

I want to change for example from...

export const paintingSchema = new Schema({
    design: string,
});

to

export const paintingSchema = new Schema({
   color: string, // <-- Property name changed here
});

I use mongoose and nodejs. Official MongoDB documentation recommends to add a second database and mirror the changes into it. But that seems overkill for my small application. Is there an easier way to achieve this?


Solution

  • This could be achieved by using $rename.

    Use this query once to rename the existing documents:

      await Painting.updateMany(
        { design: { $exists: true } }, // filter docs which contains the property
        { $rename: { design: "color" } }
      );