skip to Main Content
const obj={
  name: 'KA',
  creator: 'qQzMHzU9SPYhdYq2vswQmfeHd4j2',
  default: false,
  _id: new ObjectId('665b1dd655a3a1f154dbb74d'),
  __v: 0
}

I get the above object for mongoose query in js , and I want to convert _id to string

I tried to change it with .toString() method but it doesnot change, but I am able to change other fields

  console.log("Before Change", list);
  list._id = list._id.toString();
  list.name = "XYZ";
  console.log("After Change", list);
Before Change {
  name: 'Hritik',
  creator: 'qQzMHzU9SPYhdYq2vswQmfeHd4j2',
  default: false,
  _id: new ObjectId('665b1dd655a3a1f154dbb74e'),
  __v: 0
}
After Change {
  name: 'XYZ',
  creator: 'qQzMHzU9SPYhdYq2vswQmfeHd4j2',
  default: false,
  _id: new ObjectId('665b1dd655a3a1f154dbb74e'),
  __v: 0
}

2

Answers


  1. please try this instead of tostring

     objectId.str
    
    Login or Signup to reply.
  2. Mongoose is trying to be clever.

    Since you didn’t specify an _id field in the schema, Mongoose implicitly added one with the type ObjectId.

    When you attempt to set the _id field, mongoose tries to convert the value to match the implicitly specified type. i.e. when you convert the ObjectId to string, and then assign that string to _id, mongoose notices that it is not the expected type, but it can be converted to the expected type, so it helpfully converts the string to ObjectId for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search