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
>Solution :
You can use this
db.collection.update({
imported: null
},
[ //aggregate update
{
"$set": {
"imported": "$post.date"
}
}
])
Supported from Mongo 4.2+