I try to insert document in Node.js using TypeScript with custom _id

According to docs the _id field is any type, but I have an error saying that _id must be ObjectId type. I’m using insertOne method on collection

hi there @Szymon_N_A,

If you’re using Mongoose, I believe they set up the _id for you by default to this:

_id: mongoose.Types.ObjectId

If you try to assign any string, there might be a type problem. You could try setting this in your Schema:


or something similar (according to the type you’re string to add), and retry.

Otherwise please share the code.

Even if you’re not using mongoose but the MongoDB driver, something similar should apply. They could be declaring the _id type to ObjectId (which seems to be a class) by default.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.