'MongoDB Node.JS insertOne error: "Type 'string' is not assignable to type 'ObjectId | undefined"

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,
  })
}


Solution 1:[1]

thanks for your answers and comments. I finally figure out the solution.

async function foo() {
  await client.connect()
  const users = client.db("test").collection("users")
  const result = await users.insertOne({
    _id: "custom string",
    name: "Tom",
    age: 26,
  } as any)
  console.log(result)
}

I'm new with TypeScript and MongoDB. I don't know if this is a bug when the mongodb package comes from common JS to TypeScript.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yan
Solution 2 Andrius Urbaitis