frankiie
frankiie

Reputation: 498

Prevent old data from losing when changing document properties MongoDB

I'm a newbie to backend development and trying MongoDB as the database in my app's backend. Currently, I have 2 tables user and role which have a one-to-one relationship.

user.js

const userSchema = new mongoose.Schema(
  {
    userId: {
      type: String,
      lowercase: true,
      trim: true,
      unique: true,
      required: true,
    },
    role: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "roles",
      required: true,
    },
    userNm: {
      type: String,
      trim: true,
    },
    psitnDept: {
      type: String,
      trim: true,
    },
    password: {
      type: String,
      required: true,
      select: false,
    },
  // some other properties

role.js

const roleSchema = new mongoose.Schema(
  {
    roleCode: {
      type: String,
      trim: true,
      unique: true,
      required: true,
    },
    roleNm: {
      type: String,
      trim: true,
    },
    roleTy: {
      type: String,
      trim: true,
    },
    useAt: { type: Boolean, default: true },
    createdBy: String,
    updatedBy: String,
  },
  {
    timestamps: true,
  }
);

Now I want to change the entity-relationship between user and role to one-to-many.

newly updated user.js

const userSchema = new mongoose.Schema(
  {
    userId: {
      type: String,
      lowercase: true,
      trim: true,
      unique: true,
      required: true,
    },
    roles: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "roles",
        required: true,
      }
    ],
    userNm: {
      type: String,
      trim: true,
    },
    psitnDept: {
      type: String,
      trim: true,
    },
    password: {
      type: String,
      required: true,
      select: false,
    },
  // some other properties

How do I prevent data from losing and restore and apply the preceding one-to-one's old data to a newly updated document?

Upvotes: 0

Views: 78

Answers (1)

Smriti Shikha
Smriti Shikha

Reputation: 431

you can convert your role key first to an array of object id using update query

db.users.update({},[
    {
        '$addFields': {
            'roles': [
                '$role'
            ]
        }
    }
], {multi:true})

this will update the users data that you have to an array, which will prevent you data loss.

Upvotes: 1

Related Questions