In my code, I have a UserModel that is defined as follows:
import mongoose from "mongoose";
const UserSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
notes: [],
},
{ timestamps: true }
);
const UserModel = mongoose.model("user", UserSchema);
export { UserModel };
I also have a function that adds notes to the notes array of a user:
export default async (req, res) => {
const {
text,
title,
userId,
} = req.body;
const currentUser = await UserModel.findById(userId);
const note = new NoteModel({
title,
text,
});
currentUser.notes.push(note);
await currentUser.save();
res.json(currentUser);
};
This function works correctly. Now, I am trying to implement a function to delete notes from a user's notes array:
export default async (req, res) => {
const { id: noteId } = req.params;
const user = await UserModel.findById(req.body.userId);
user.notes.pull(noteId);
await user.save();
res.json(user);
};
However, the note is not getting deleted as expected. I have tried the following methods:
await user.notes.pull(noteId)
.(with and without awaiting)
user.notes.pull({_id: noteId)}
.
UserModel.update(
{ _id: userId},
{
$pull: {
notes: { _id : noteId }
}
},
- Trying to remove the note using JavaScript array methods like filter, splice, slice, and spread.
Unfortunately, none of these approaches seem to be working in deleting the note. What could be the issue here?