首页 > 解决方案 > MongoDB Mongoose 如何从数组中删除对象

问题描述

var UserSchema = new mongoose.Schema({
   //Irrelevant code
   profile:
   { 
    requests: [{ sender: String, id: String,  hasSelected: Boolean, value: Boolean}]
   }
});

该对象是跟踪好友请求,我希望它在被接受或拒绝后从请求数组中完全删除。我已经尝试了一大堆东西,但没有任何东西可以删除它。目前有这个代码:

User.updateOne({ id: user.id },
              { "$pull": { "profile": { "requests": { "id": targetId } } }  },
              { "multi": true },
              function(err,status) {
                if(err){console.log("Could not delete the friend request");}
                else{ 
                  console.log("Sucessfully deleted friend request from: " + user.name);}
               }
              );

它总是说它已在日志中删除,但是当我检查 mongoDB 时,请求仍然存在。

标签: node.jsmongodbmongoose

解决方案


尝试 $elemMatch 删除特定对象。

 User.updateOne(
 { id: user.id },
 { $pull: { "profile.requests": { $elemMatch: { id: targetId } } } },
 { multi: true },
 function (err, status) {
 if (err) {
  console.log("Could not delete the friend request");
  } else {
  console.log("Sucessfully deleted friend request from: " + user.name);
 }
 }
 );

推荐阅读