【问题标题】:mongodb pull/delete not workmongodb拉/删除不起作用
【发布时间】:2018-06-06 10:48:49
【问题描述】:

我在删除数组中的对象时遇到了一些问题 该 API 的结果总是“修改已删除” 如果“iduser”无效或有效 以及Modification doc和Account doc中没有删除的对象

这是我的主要文档

let Account = new Schema({
  firstName       : {type : String, required : true},
  lastName        : String,
  email           : {type : String, required : true},
  profilePicture  : {type : String, required : true},
  gender          : {type : String, required : true},
  id              : {type : String, required : true},
  location        : String,
  birthday        : Date,
  experiences     : [Number],
  achievements    : [Number],
  modifications   : {type : [Schema.Types.ObjectId], ref : 'Modification'}
},{usePushEach: true});

这是我要删除的数组对象

let modificationSchema = new Schema({
  desc      : {type : String, required : true},
  make      : {type : String, required : true},
  type      : {type : String, required : true},
  photo     : {type : String, required : true},
  postDate  : {type : Date,   required : true},
  likes     : {type : [Schema.Types.ObjectId], ref : 'Like'},
  comments  : {type : [Schema.Types.ObjectId], ref : 'Comment'}
},{usePushEach: true});

这是我从 Account 对象中删除修改对象的代码

api.put('/modification/:iduser/:idmodif' , (req,res) =>{
    Account.findOneAndUpdate({"email":req.params.iduser},
      { $pull : { modifications : { _id : req.params.idmodif}}}, 
function(err,model){
        if(err){
          return res.send(err);
        }else{
          res.json({message : "modification deleted"});
        }
      }
    );
  });

感谢您的帮助:)

【问题讨论】:

标签: javascript node.js mongodb api


【解决方案1】:

你可以使用标准技术

api.put('/modification/:iduser/:idmodif' , (req,res) =>{
    Account.findById({_id:req.params.iduser}, 
function(err,model){
        model.modifications = null;
        model.save(function(err,result){
        if(err){
          return res.send(err);
        }else{
          res.json({message : "modification deleted"});
        }
        });
      }
    );
  });

【讨论】:

  • 感谢您的帮助,但该技术仅删除了 "Account.modification" 中的引用对象 (_id) 。并且“修改文档”中的真实对象仍然存在。看看我的架构。
猜你喜欢
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
相关资源
最近更新 更多