【问题标题】:not able to use $pull (Mongoose) to remove an object in an array for a user model无法使用 $pull (Mongoose) 为用户模型删除数组中的对象
【发布时间】:2020-05-09 01:03:45
【问题描述】:

我尝试了各种方法和方法来做到这一点,我正在尝试使用 $pull 方法

这是我的用户对象

我以前只有用户对象中的对象ID,但现在我要删除一个完整的对象,我搜索发布的ID,然后尝试将其拉出

    router.delete('/testing', (req, res, next) => {
    postModel.findByIdAndRemove(req.query.postid, (error, returnedDocuments) => {
        if (error) return next(error);

        userModel.findOneAndUpdate(
            // { email: req.query.email, posts: req.query.postid },
            { email: req.query.email },
            { $pull: { posts: { number: mongoose.Types.ObjectId(req.query.postid) } } },
            { new: true },
            function(error, user) {
                if (error) {
                    res.json(error);
                }
                console.log(`Post id ===== ${req.query.postid}`);
                console.log(`Email===== ${req.query.email}`);
                console.log(`returning user====${user}`);
                res.json('Successfully updated user');
            }
        );
    });
});

帖子正在从帖子模型中删除,但我无法从用户发布的数组中删除该对象。

任何关于为什么会发生这种情况的替代解决方案或见解将不胜感激。

【问题讨论】:

  • { $pull: { posts: { number: req.query.postid } } } ==> posts 数组中是否有一个名为 number 的属性。因为它不在您提供的示例中。
  • 对不起,太奇怪了……我又复制了一遍。
  • 我也试过{ $pull: { "posts.$.number" : req.query.postid }},但没有cookie :(
  • 对于帖子。$.number 我收到一个错误:"errmsg": "The positional operator did not find the match needed from the query.", 可能是因为我需要输入对象或其他什么?
  • @jcx3x 是 req.query.postid 字符串还是 ObjectId

标签: javascript reactjs database mongodb mongoose


【解决方案1】:

问题是 MongoDB 在值之前比较类型,并且没有应用隐式类型转换,所以没有:

{ $pull: { posts: { number: req.query.postid } } }

你需要运行:

{ $pull: { posts: { number: mongoose.Types.ObjectId(req.query.postid) } } }

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 2021-09-12
    • 2021-08-11
    • 1970-01-01
    • 2016-10-28
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多