Midhun
Midhun

Reputation: 1167

How do I update the existing documents' schema?

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?

Upvotes: 1

Views: 50

Answers (2)

Midhun
Midhun

Reputation: 1167

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

Thanks for the help @prasad_

Upvotes: 0

divyesh makvana
divyesh makvana

Reputation: 449

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

Upvotes: 1

Related Questions