Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
How to remove a subdocument from a schema when a button is clicked? - Mongoose

Unable to figure this out. My project is pretty much a website with listings that you can comment on, all the comments show through EJS. Full CRUD works, except when it comes to deleting the single comment. (listings can be deleted fine) There is a delete button for each comment.The comments are embedded into the schema. I've been trying various methods but it is erroring out.

My listing & comment schema:

const commentSchema = new Schema({
    content: String,
},{
    timestamps: true
});

const gigSchema = new Schema({
    title: {
        type: String,
        required: true,
    },
    price: {
        type: Number,
        required: true,
    },
    description: {
        type: String,
        required: true,
    },
    comments: [commentSchema]
}, {
    timestamps: true
});

my routes:

router.post('/:id/comments', commentsCtrl.commentsGig.create);

router.delete('/:id/comments', commentsCtrl.commentsGig.destroy);

i've tried

const destroy = (req, res) => {
  db.Gig.findById(req.params.id, (err, gigs)=>{
    if (err) return res.send(err);
    gigs.comments[0].remove();
    gigs.save(function(err){
      res.redirect(`/gigs/${gigs._id}`)
    })
  })

and get errors, i've found pull methods... but my code is not working. I get this error when trying to 'delete' the comment 'Cannot DELETE /gigs/'

this is my delete button just in case

  <form class = 'secondary-content' action="/gigs/<%= gigs.comments._id %>?_method=DELETE" method="POST">
              <input type="submit" value="Delete" /></form>

any help would be appreciated!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!