Removing a child element in subdocument not working

I’m fairly new to Mongoose and don’t think my approach on deleting an item in a subdocument is the right one.

I have the following schema setup:

  • POSTing json to express using jQuery
  • Kraken.js CSRF Handling
  • Express can't upload file, req.files is undefined
  • Using Sinon to stub chained Mongoose calls
  • Impossible to get property from mongoose object
  • the connect middleware for coffeescript?
  • //DEPENDENCIES
    var mongoose = require('mongoose');
    
    
    var contactSchema = new mongoose.Schema({
      name:{type:String},
      age:{type:Number}
    });
    
    var phoneSchema = new mongoose.Schema({
      number:{ type: String },
      phoneType:{ type: Number }
    })
    
    var memberSchema = new mongoose.Schema({
    
      firstname: {
        type: String
      },
      lastname: {
        type: String
      },
      phone:[phoneSchema],
      contacts:[contactSchema]
    
      });
    
    //RETURN MODEL
    
    module.exports = mongoose.model('member', memberSchema);
    

    To remove an item from the phone, in my Express API, I first find the parent then reference “remove” for the child ID, like this. But it does not work.

    router.route(‘/owner/:ownerId/phone/:phoneId’)

    .delete(function(req, res){
      Member.findOne({_id: req.body.ownerId}, function(err, member){
          member.phone.remove({_id: req.body.phoneId}, function(err){
            if(err)
              res.send(err)
            res.json({message: 'Success! Phone has been removed.'})
        });
      });
    });
    

  • Error: failed to serialize user into session. Wrong function passed to serializeUser()?
  • How do I update a property with the current date in a Mongoose schema on every save?
  • Force requests over https in Express/Node
  • Socket.io 1.0 + express 4.2 = no socket connection
  • Passing error message to template through redirect in Express/Node.js
  • Define mongoose and Schema only ones
  • One Solution collect form web for “Removing a child element in subdocument not working”

    Figured out that I was looking for req.body and was actually needing req.params.

    Also found right syntax on Mongoose docs:

    router.route('/owner/:ownerId/phone/:phoneId')
    
    .delete(function(req, res){
      Member.findOne({_id: req.params.ownerId}, function(err, member){
    
          member.phone.id(req.params.phoneId).remove();
    
          member.save(function (err) {
            if (err) return handleError(err);
            console.log('the sub-doc was removed');
          });
    
    
      });
    });
    
    Node.js is the Best Javascript runtime in the world.