Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb+mongoose update documents with date from other field = cast to date error

okay so i have some documents that are missing some data, im trying to update them like this;

await MyModel.updateMany(
  { imported: null },
  { $set: { 
    "imported": "$post.date"
  }}
)

but i get cast to date error.

so i decided to work with a single document to figure out why that is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

so first lets see what inside post.date

console.log(
  await MyModel.find({ _id: '5c2ce0fa527ad758bdb29506' })
               .select('post.date imported')
)
[
  {
    post: { date: 2018-11-29T18:02:25.000Z },
    _id: new ObjectId("5c2ce0fa527ad758bdb29506")
  }
]

okay, so i though what happens if i copy the date and hardcode it, like so:

await MyModel.updateMany(
  { _id: "5c2ce0fa527ad758bdb29506" },
  { $set: { 
    "imported": "2018-11-29T18:02:25.000Z"
  }}
)

that works just fine, but when i try to use the value from $post.date, like this:

await MyModel.updateMany(
  { _id: "5c2ce0fa527ad758bdb29506" },
  { $set: { 
    "imported": "$post.date"
  }}
)

it results in

Cast to date failed for value "$post.date" (type string) at path "imported"

i have tried to use $dateFromString and $toDate but with no luck, but i feel like mongoose is trying to validate the string value "$post.date" and not interpret it as mongo would even through the mongoose schema has no validators defined.

so i tried adding { runValidators: false }, but it feels like it is ignored

await MyModel.updateMany(
  { _id: "5c2ce0fa527ad758bdb29506" },
  { $set: { 
    "imported": "$post.date"
  }},
  { runValidators: false }
)

as the error is the same.

im running mongoose v. 6.2.0 and mongodb v. 4.2.18

any inputs are much appreciated

>Solution :

You can use this

db.collection.update({
  imported: null
},
[ //aggregate update
  {
    "$set": {
      "imported": "$post.date"
    }
  }
])

Supported from Mongo 4.2+

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading