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
please try this instead of tostring
Mongoose is trying to be clever.
Since you didn’t specify an
_id
field in the schema, Mongoose implicitly added one with the typeObjectId
.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.