首页 > 解决方案 > MongoDB $pull 查询无法正常工作

问题描述

伙计们,我想用 $pull qıery提出取消关注请求,但它不起作用。如何解决这个问题?

当我想关注请求用户时,此方法也适用于$push查询,但不适用于$pull.

我的 app.js:

app.post('/unfollow/:id', function(req, res){

  User.find(req.user
  
  ).exec(function(err, user){
  
  if(err){
    console.log(err);
  }
    
    User.find({"username":req.params.id}, function(err, friend){
      
      if(err){
        console.log(err);
      }
    User.update(user,{$pull: { follow: friend}}, function(err){
      if(err){
      console.log(err);
    }else{
      res.send("Success")
    } 
    });
  });
  });
  });

这是我的用户关注的样子:

{ follow:
   [ 5edfe8f3bfc9d677005d55ca,
     5edfe92fbfc9d677005d55cc,
     5ee2326cc7351c5bb0b75f1a ],

我将从这个数组中获取朋友 ID。

还有我的用户模型(关注部分):

follow:[{
    type: ObjectId,
}]

如果 pull 不起作用,您能否建议我查询或取消关注请求的方法。

标签: node.jsmongodb

解决方案


User.find({ username: req.params.id }会返回一个文档,但看起来你确实在字段中存储ObjectId了 s 。follow我除了改成 $pull: { follow: friend }应该$pull: { follow: friend._id }可以解决问题。


推荐阅读