0

After importing data into mongo, fields that were supposed to be of type null ended up being strings "null", is there a command or query to replace all instances of that string with a null value?

I have something like this

TestModel.updateMany({ test: 'null' },{ $set: { test: null } })

But it throws this error

CastError: Cast to ObjectId failed for value "null" at path "test" for model "TestModel"

I tried it in other fields where they are all string and it works, but the field "test" can be an Objectid or a null

EDIT:

document:

const TestSchema = new Schema({
    test: { type: Schema.Types.ObjectId}
});
module.exports = db.model('TestModel', TestSchema);
Bruno Puccio
  • 143
  • 1
  • 8
  • Please post a sample document showing the `test` field. Also, specify where you are running this command from (shell, node, Mongoose, etc.). – prasad_ Sep 15 '20 at 16:16
  • @prasad_ i tried running that command using mongoose, but i am looking for a solution on either mongoose or the shell – Bruno Puccio Sep 15 '20 at 16:38
  • That command may work using shell. Mongoose is trying to convert "null" to an objectId, shell won't. ```db.TestModel.updateMany({ test: 'null' },{ $set: { test: null } }, {multi: true})``` – GitGitBoom Sep 15 '20 at 16:41
  • Does it need to be explicitly set to `null`, or is having the field omitted from the document sufficient? – Joe Sep 16 '20 at 06:00

1 Answers1

0

Use this code:

TestModel.updateMany({ test: 'null' }, { $set: { test: undefiend } })
Mark Huk
  • 2,379
  • 21
  • 28
mohammad Naimi
  • 2,259
  • 1
  • 5
  • 15