MEAN-Stack MongoDB 子数组删除 - 在 IDE 中有效,在 API 中无效

MEAN-Stack MongoDB Sub Array Delete - Works in IDE, not in API

我存储了一个 [user] 文档,其中包含嵌套的 sub-array [profiles],[favorites]。我只是想 delete($pull) 根据收藏夹名称从给定的配置文件中添加收藏夹。

{
"_id" : ObjectId("558d53eebdd9804820090fa1"),    
"name" : "Frank",
"email" : "Frank@FrankTheTank.com",   
"profiles" : [ 
    {
        "avatar" : "div-male",
        "age" : "35",
        "gender" : "Male",
        "profilename" : "Oly Lifter",
        "_id" : ObjectId("558d5404bdd9804820090fa2"),
        "favorites" : [ 
            {
                "name" : "Power Clean"
            }, 
            {
                "name" : "Hang Clean"
            }, 
            {
                "name" : "Clean and Jerk"
            }
        ],
        "createdAt" : ISODate("2015-06-26T13:30:44.661Z")
    }
    ],
    "createdAt" : ISODate("2015-06-26T13:30:22.884Z"),
    "role" : "user",
    "__v" : 0
}

使用 MongoDB IDE robomongo,我能够使用此

成功地从已知用户和配置文件 ID 中删除最喜欢的项目
 db.users.update($find: {
        'profiles': {
            'profiles._id': ObjectId("558d5404bdd9804820090fa2")
        },
        {
            $pull: {
                'profiles.$.favorites': {
                    'name': 'Hang Clean'
                }
            }
        })

但是,当我使用以下语法从我的服务器 API 调用时,我收到一个错误,请注意 req.body._id = "558d5404bdd9804820090fa2"req.body.favorites.name = "Hang Clean"

User.findByIdAndUpdate(_user._id, {
    'profiles._id': req.body._id
    }, {
    $pull: {
        'profiles.$.favorites': {
            'name': req.body.favorites.name
        }
    }
    }, {
    safe: true,
    upsert: true
    },
    function(err, model) {
    if (err) {
        console.log(err);
        return res.status(500).send('Error Deleting Profile');
    }
    return res.status(200).send('Profile Deleted!');
    });

尝试使用 findOneAndUpdate() method since you are supplying the findByIdAndUpdate() method with the wrong parameters: the second argument { 'profiles._id': req.body._id } should be part of the first query object hence you need to use the findOneAndUpdate() 方法进行更新,确保将字符串 ID 转换为 ObjectId:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId(_user._id),
    profileId = mongoose.Types.ObjectId(req.body._id),
    query = {
        "_id": id,
        "profiles._id": profileId 
    },
    update = {
        "$pull": { 
            "profiles.$.favorites": { "name": req.body.favorites.name }
        }
    },
    options = { "multi": true, "upsert": true };

User.findOneAndUpdate(query, update, options, function(err, model) {
     if(err){
        console.log(err);
        return res.status(500).send('Error Deleting Profile');
     }
     return res.status(200).send('Profile Deleted!');       
});