Issue
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.
Solution
This is expected behaviour. When you add an object to MongoDB then mongoose will automatically assign an _id
property of type ObjectId
to it.
To remove this feature pass the _id: false
property into your schema for the relevant object like so:
const NotiticationSchema = new Schema<Notitication>({
//...
teamId: { type: String, required: true },
result: {
type: {
accepted: { type: Boolean, required: true },
motivation: { type: String, required: true }
},
default: null,
_id: false //< here
}
});
Answered By - jQueeny
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.