2015-10-30 55 views
1

我正在构建使用Mongodb和mongoose的Node.js express RESTfull API。使用Mongoose中间件级联删除阵列删除钩子

这是我的架构:

var UserSchema = new mongo.Schema({ 
    username: { type: String }, 
    password: { type: String, min: 8 }, 
    display_name: { type: String, min: 1 }, 
    friends: { type: [String] } 
}); 

UserSchema.post('remove', function(next){ 
    console.log({ friends: this._id }); // to test if this gets reached (it does) 
    UserSchema.remove({ friends: this._id }); 
}); 

这是删除用户的功能:

.delete(function(req, res) { 
    User.findById(req.params.user_id, function(err, user) { 
    if (err) { 
     res.status(500); 
     res.send(err); 
    } else { 
     if (user != null) { 
     user.remove(); 
     res.json({ message: 'User successfully deleted' }); 
     } else { 
     res.status(403); 
     res.json({ message: 'Could not find user.' }); 
     res.send(); 
     } 
    } 
    }); 
}); 

我需要做的是,当一个用户被删除,他或她的_id(字符串)也应该从所有其他用户的朋友阵列中删除。因此,架构中的删除挂钩。

现在用户被删除和钩被触发,但用户_id不会从朋友阵列(邮差测试)删除:

[ 
    { 
     "_id": "563155447e982194d02a4890", 
     "username": "admin", 
     "__v": 25, 
     "password": "adminpass", 
     "display_name": "admin", 
     "friends": [ 
      "5633d1c02a8cd82f5c7c55d4" 
     ] 
    }, 
    { 
     "_id": "5633d1c02a8cd82f5c7c55d4", 
     "display_name": "Johnybruh", 
     "password": "donttouchjohnsstuff", 
     "username": "John stuff n things", 
     "__v": 0, 
     "friends": [] 
    } 
] 

要这样:

[ 
    { 
     "_id": "563155447e982194d02a4890", 
     "username": "admin", 
     "__v": 25, 
     "password": "adminpass", 
     "display_name": "admin", 
     "friends": [ 
      "5633d1c02a8cd82f5c7c55d4" 
     ] 
    } 
] 

试图找出它,我已经看了Mongoosejs Documentation,但猫鼬doc示例不包括删除钩子。另外this stackoverflow qestion但这个问题似乎是从其他模式中删除。

我想我在做错了钩子,但我似乎无法找到问题。

在此先感谢!

编辑:

我无法得到通过cmlndz第一建议工作,所以我最终获取所有的文件与包含待删除的用户ID阵列并从他们单拉接一个:

删除功能现在包含此位的代码,不会魔法:

// retrieve all documents that have this users' id in their friends lists 
User.find({ friends: user._id }, function(err, friends) { 
    if (err) { 
    res.json({ warning: 'References not removed' }); 
    } else { 

    // pull each reference to the deleted user one-by-one 
    friends.forEach(function(friend){ 
     friend.friends.pull(user._id); 
     friend.save(function(err) { 
     if (err) { 
      res.json({ warning: 'Not all references removed' }); 
     } 
     }); 
    }); 
    } 
}); 

回答

2

你可以使用$pull找到包含“ID”的“朋友”阵列中的所有文件 - 或者 - 找到任何matchin g文件并将“ID”从阵列中逐一弹出。