7

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,
  })
}
4
  • 1
    Why do you have to overwrite the default _id field if it's already auto incrementing ? If you need a string, can't you just add another field ? Commented Oct 12, 2021 at 2:41
  • If you want to use a custom string for _id you need to specify that in the schema mongoosejs.com/docs/guide.html#_id otherwise it expects specifically a ObjectId or a string version of an object id (specific length). Did you do that in your schema? Commented Oct 12, 2021 at 2:55
  • @Psidom For some reason, I just want it to be string... Commented Oct 12, 2021 at 3:38
  • @AlexanderStaroselsky I've gone through this link you paste. It seems that this is not the official driver provided by MongoDB. I'm wondering if I can achieve this using official mongodb package? Commented Oct 12, 2021 at 3:39

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.