Removing a child element in subdocument not working

99封情书 提交于 2019-12-12 01:27:51

问题


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:

//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.'})
    });
  });
});

回答1:


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');
      });


  });
});


来源:https://stackoverflow.com/questions/41682734/removing-a-child-element-in-subdocument-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!