In my code, I have a function that updates documents in mongoDB. After manipulating the data, I use mongoose's findOneAndUpdate
function to update the desired document. To fetch only specific fields from the saved data, I set new:true
and define an object named userReturnFormat
for projection. Here is an example of the code:
const userReturnFormat = {
email: 1,
name: 1,
surname: 1,
_id: 0
}
const updatedUser = (await UserModel.findOneAndUpdate(
{ registerId: params.user.registerId },
{ $set: data },
{ new: true, projection: userReturnFormat }
)) as User
In the userReturnFormat
object, I specifically set the _id
field to false
. When I include {_id:0}
in the projection, it successfully excludes the _id
field. Although I attempted to directly specify the projection within the update operation, it still returned the _id
field when marking any property as true
. While I can remove the _id
field using the delete operand after updating the document, I prefer to solely rely on the projection for this purpose.
{_id: 0 }
used as a projection:
const updatedUser = (await UserModel.findOneAndUpdate(
{ registerId: params.user.registerId },
{ $set: data },
{ new: true, projection: { _id: 0 } }
)) as User
RESULT:
{
email: ‘<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066c5962696346637e676b766a212d2f">[email protected]</a>’,
password: ‘HASHED_PASSWORD’,
name: ‘JOHN’,
surname: ‘DOE’,
type: ‘example’,
createdAt: 2024-01-03T12:57:20.972Z,
updatedAt: 2024-01-04T07:30:27.153Z
}
Using the delete
operand:
const updatedUser = (
await UserModel.findOneAndUpdate({ registerId: params.user.registerId }, { $set: data }, { new: true, projection: userReturnFormat })
)?._doc
delete updatedUser._id
RESULT:
{
email: ‘<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42281d262d2702273a232f322e276c212d2f">[email protected]</a>’,
name: ‘JOHN’,
surname: ‘DOE’,
}