Well, I have used MongoDB in a while but I don't know how to handle this situation.
The scenario is: I have data inserted in MongoDB. I have exported the data in JSON format, and it is something like:
[
{
"_id": { "$oid": "60ff324f41c4d5b96054390d" },
"field": {
"due_date": { "$date": "2021-11-03T00:09:18.271Z" }
}
}
]
You can see that :
_id
is{ "$oid": "60ff324f41c4d5b96054390d" }
anddate
is{ "$date": "2021-11-03T00:09:18.271Z" }
.
So, the problem is trying to insert in another DB using Mongoose. I want to test some funcionality isolated so I wan't these values in other environment, so I have used insertMany()
with the JSON previously exported.
(Maybe there is a more elegant way to import a JSON file but is only for testing purposes)
await model.insertMany(JSON.parse(fs.readFileSync('./data.json').toString()))
But the problem is here: It throws an error because my schema says that _id
is an ObjectId
and due_date
is a Date
object but they are actually read as objects: {$oid: ""}
and {$date: ""}
ValidationError: model validation failed: _id: Cast to ObjectId failed for value "{ '$oid': '60ff324f41c4d5b96054390d' }" (type Object) at path "_id", field.due_date: Cast to date failed for value "{ '$date': '2021-11-03T00:09:18.271Z' }" (type Object) at path "field.due_date"
So the question is: Is there any way to cast the $oid
and $date
objects using mongoose while inserting?
Also, I have managed to insert the values using a very ugly script iterating over each value and checking if the object is $oid
or $date
and modifying the values... but it works.
So the question is not: "Is there a workaround to do this?" but "Is there a way to do it directly with mongoose functions as insertMany
and casted automatically?"
Thanks.
CodePudding user response:
The {"$oid": ...}
and {"$date":...}
constructs are MongoDB extended JSON notation, since JSON does not have any type for Date
or ObjectId
.
In order to insert those values, you will need to use a JSON parser that knows about this extended format.
One possibility is the json_util
that is included with bson
.
Or you can use mongoimport to read the JSON file and do the inserts for you.