I’m developing an endpoint that accepts a basic invitation, I need to get a notification by an id provided in the parameters (suing express), and then update his result
field. The interface/schema is like this:
const NotiticationSchema = new Schema<Notitication>({
title: { type: String, required: true },
description: { type: String, default: null },
date: { type: Date, default: Date.now() },
type: { type: String, required: true },
navigation: {
type: String,
enum: NotificationNav,
required: true
},
navigationId: {
type: String,
enum: NotificationIds,
required: true
},
teamId: { type: String, required: true },
result: {
type: {
accepted: { type: Boolean, required: true },
motivation: { type: String, required: true }
},
default: null
}
});
This is the code that I’m currently using:
const notification = await NotiticationModel.findByIdAndUpdate(req.params["id"]!, { $set: { result: { accepted: true, motivation: null } } });
The expected output should be:
{
...
"result": {
"accepted": true,
"motivation": null
}
}
What NotiticationModel.findByIdAndUpdate()
does:
{
...
"result": {
"accepted": true,
"motivation": null,
"_id": {
"$oid": "65b23b495a60bda2c6e67996"
}
}
}
I’ve never encountered this behaviour, anyone can help?
P.S. I’ve already asked AI, it didn’t give any useful advice.
2
Answers
For your case, you should use the updateOne in stead of the findByIdAndUpdate
The findById I think replaces the entire document with new one.
Example
This is expected behaviour. When you add an object to MongoDB then mongoose will automatically assign an
_id
property of typeObjectId
to it.To remove this feature pass the
_id: false
property into your schema for the relevant object like so: