本文介绍了删除子文档中的子元素不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Mongoose的新手,不认为我删除子文档中项目的方法是正确的.

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

我具有以下架构设置:

//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);

要从电话中删除项目,请先在我的Express API中找到父项,然后为子项ID引用删除",如下所示.但这是行不通的.

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

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

推荐答案

发现我正在寻找req.body,实际上需要req.params.

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

还在Mongoose文档上找到正确的语法:

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


  });
});

这篇关于删除子文档中的子元素不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:57