Search code examples
mongodbmongoosemongoose-schema

Data type not changing in mongo DB after I made changes to mongoose schema


I recently made changes to my mongoose schema from String to Number. When I read data from db, it show as Number but when I try making filters based on the changed property, I don't get any document that was saved before the schema changes were made. When I check using Robo 3T, I see the data types are still showing string. I wish to change all to Number. The data type doesn't seem to change even after I make updates to the document.

const mySchema = new mongoose.Schema(

 {
    status: {
      type: Number,
      default: 1
    }
}...)

Here is how it looks like in the DB

enter image description here

I'll appreciate any help


Solution

  • I switched from using findOne

    mySchema.statics.updateStatus = async function(id, status){
      try{
        const record = await this.findOne({_id: id});
        if(record){
          record.status = parseInt(status);
        }
        const updatedRecord = await record.save();
        return updatedRecord;
      }catch(err){
        return null;
      }
    }
    

    To using fineOneAndUpdate

    mySchema.statics.updateStatus = async function(id, status){
      try{
        const record = await this.findOneAndUpdate({ _id:id }, {status}, {
          returnOriginal: false
        });
      
        return record;
      }catch(err){
        return null;
      }
    }
    

    And it updated the data type in the DB.