【问题标题】:How to find and delete a particular object in an Array of Object in Mongoose如何在 Mongoose 的对象数组中查找和删除特定对象
【发布时间】:2018-11-13 00:28:34
【问题描述】:

我有以下 Mongoose 用户架构:

postCreated:{
    type: Array,
    default: []
}

其中包含属于该用户的帖子对象数组。我计划执行以下操作:当我删除特定帖子时,我将该帖子的 id 和创建的用户的用户名传递给后端,并希望它将帖子从 Post 模式和 postCreated 中删除所属用户

server.del('/posts',(req,res,next)=>{
    const {id,username} = req.body;
    User.findOne({username}).then(user => {
        console.log(user.postCreated)
        user.postCreated.filter(post => {
            post._id !== id;
        });
        console.log(user.postCreated)
    });
    Posts.findOneAndRemove({_id: id}).then((post) => {
        if(!post){
            return next(new errors.NotFoundError('Post not found'));
        }
        res.send(post);
    })
    .catch((e) => {
        return next(new errors.BadRequestError(e.message));
    });
});

但是,帖子只是从 Post Model 中删除,而不是从 User Model 的 postCreated 中删除,这意味着 user.postCreated.filter 不起作用。

感谢 Jack,我尝试了以下方法,但似乎没有解决问题:

    User.update(
        { username },
        { $pull: { postCreated: {_id: id} } },
        { multi: true }
    );

有什么办法可以解决这个问题吗?

非常感谢任何帮助。

【问题讨论】:

  • 你需要使用$pull从数组中移除一个元素

标签: node.js mongodb mongoose


【解决方案1】:

如果您想按照以前的方式进行操作,则需要将您的 postCreated 数组存储回其中,然后保存用户:

User.findOne({username}).then(user => {
    console.log(user.postCreated)
    user.postCreated = user.postCreated.filter(post => {
        post._id !== id;
    });
    console.log(user.postCreated);
    user.save();
});

但如果您以后需要用户对象,最好的方法是 findOneAndUpdate。

【讨论】:

  • 这对我有用。但是有什么替代品吗?
【解决方案2】:

你可以使用猫鼬$pull

使用:https://docs.mongodb.com/manual/reference/operator/update/pull/

User.update(
    { username },
    { $pull: { postCreated: id } },
    { multi: true }
);

这应该可以解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-13
    • 2015-09-16
    • 1970-01-01
    • 2015-04-08
    • 2020-03-19
    • 2014-05-13
    • 2015-07-18
    • 2019-11-02
    相关资源
    最近更新 更多