How can I rename the id field and convert it from a string to an ObjectId on the way into mongo? I would like to do this work on the database rather than in the application.
I am converting mongo’s _id
field from an ObjectId
to a string and renaming it to id
on the way out of the database. How can I do the reverse when I am updating a record?
export async function updateEvent( id: string, event: IEvent ) {
const _id = new ObjectId(id)
// how can I get rid of this
const _event: any = event
_event._id = new ObjectId(event.id)
delete _event._id
await db()
.collection('events')
.updateOne(
{ _id },
_event,
// and do the work here instead
)
}
Below I am turning the _id
field into a string and renaming it to id
before passing the record to the rest of the application. How can I do the reverse on the way back into the database?
export async function retrieveEvent( id: string ) {
const _id = new ObjectId(id)
const event = await db()
.collection('events')
.findOne(
{ _id },
{
projection: {
_id: 0,
id: {$toString: "$_id" },
name: 1,
}
}
)
return event
}