从mongoDB数组中删除值

时间:2016-01-03 00:53:41

标签: mongodb express mongoose stack mean

您好我正在尝试从mongoDB中删除一个值,但是代码没有删除特定值,而是从架构中删除所有用户lol。

var mongoose = require('mongoose');
var User = require('../../models/UserModel');

module.exports.unfollow = function(req, res){

    var thefollowee = req.body.followee;
    var thefollower = req.body.follower;


    User.find({_id: thefollower}).remove({following: thefollowee}).exec();

    User.find({_id: thefollowee}).remove({followers: thefollower}).exec();

    res.json({ message: 'Unfollowed'});




};

被访者指的是被跟踪者的身份, 跟随者指向跟随被跟随者的用户的ID。

1 个答案:

答案 0 :(得分:0)

好的,所以我通过使用$ pull方法得到它

var mongoose = require('mongoose');
var User = require('../../models/UserModel');

module.exports.unfollow = function(req, res){

    var thefollowee = req.body.followee;
    var thefollower = req.body.follower;


        User.findByIdAndUpdate(thefollowee, { $pull: { followers: req.body.follower }}, function (err, user) {

            if (err)

            return handleError(err);

        });

        User.findByIdAndUpdate(thefollower, { $pull: { following: req.body.followee }}, function (err, user) {

            if (err)

            return handleError(err);

        });

    res.json({ message: 'Unfollowed'});




};