Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

273
Vistas
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.

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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use this

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

Supported from Mongo 4.2+

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda