javascript - 无法使用 $pull (Mongoose) 删除用户模型数组中的对象

标签 javascript reactjs database mongodb mongoose

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

这是我的用户对象

enter image description here

我以前只有用户对象中的对象 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');
            }
        );
    });
});

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

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

最佳答案

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

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

你需要运行:

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

关于javascript - 无法使用 $pull (Mongoose) 删除用户模型数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867023/

相关文章:

javascript - 使用抽屉导航时 react 导航标题不可见

java - 创建目录 Oracle/JDBC 失败

javascript - Node js 的谷歌端到端加密

javascript - 使用PHP脚本仅在主页上执行JS <script>标签

javascript - 从 onClick 事件捕获链接

javascript - 如何在 react 中水平对齐2行?

javascript - 未捕获的类型错误 : Cannot read property 'name' of undefined - Reactjs

php - 如何通过单个查询检查多个 ID 是否存在

mysql - 为什么我的连接查询没有给出三个表的预期结果

javascript - AngularJS:从 php 脚本获取 JSON