I try to insert one document into the collection, but I get this error when I specify the _id field of the inserted document. So how can I insert a document with _id of a type other than ObjectId?
The following code gives me that error. When I remove the _id, everything goes fine but the _id will be generated automatically. I just want it to be a string type. I know this is possible. I can make _id string using MongoDB shell.
async function foo() {
const users = client.db("test").collection("users")
users.insertOne({
_id: "a string",
name: "Tom",
age: 26,
})
}
If you type your collection with _id: string it should work
type usertype = {
_id: string,
name: string,
age: number
}
async function foo() {
await client.connect()
const users = client.db("test").collection<usertype>("users")
const result = await users.insertOne({
_id: "custom string",
name: "Tom",
age: 26,
})
console.log(result)
}
that should give you the result you're looking for
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With