Currently have something like this in my mongoose application:
const user = await User.findById(request.params.id)
Whenever I console.log(user)
, I get the entire document object, alongside the _id: new ObjectId("idstring")
property. There is no reference to id
but rather to just _id
.
However when I console.log(user.id)
I get the returned _id in string format.
How is this possible? Do mongoose models automatically convert the objectID to a string when you call "id" to the object?
CodePudding user response:
Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.
Because of the virtuals, you are getting the results. So, id is a getter that gives the string's representation of the field _id
.
Check here for documentation.