Home > Mobile >  How do I update the existing documents' schema?
How do I update the existing documents' schema?

Time:02-18

I'm using mongoose to do some MongoDB operations.

At the beginning the category was number,

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
 category: {
    type: Number,
 }
})
module.exports = mongoose.model("SampleSchema", sampleSchema);

Now the category changed to String, So I changed the model like this

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sampleSchema = new Schema({
 category: {
    type: String,
 }
})
module.exports = mongoose.model("SampleSchema", sampleSchema);

The problem is, I have already inserted 200 records into this collection. Is there any way to update the category value with a string and change its type to string?

CodePudding user response:

Please get All data by query and update it one by one in loop.

Like:

db.tableName.find( { 'status' : { $type : 1 } } ).forEach( function (val) {   
  val.status = new String(val.status);
  db.tableName.save(val);
});

CodePudding user response:

I changed the category to mixed, that's working fine with numbers and string.

Thanks for the help @prasad_

  • Related