简体   繁体   English

从嵌入式MongoDB文档中的数组中提取对象

[英]Pull objects from array in embedded MongoDB document

I've been unable to figure out a way to to remove objects from arrays in embedded mongoDB documents. 我一直无法找到一种从嵌入式mongoDB文档中的数组中删除对象的方法。 My schema holds a user and a list of flower objects. 我的架构包含一个用户和一个花对象列表。 It looks like this: 看起来像这样:

const UserSchema = new Schema({
    name    : {
        type     : String,
        required : true
    },
    flowers : [
        {
            name       : {
                type     : String,
                required : true
            },
            water_freq : {
                type     : Number,
                required : true
            }
        }
    ]
});

I've managed to add flower objects like so: 我设法像这样添加花对象:

router.post('/:id/flowers/add', (req, res) => {
    const { name, water_freq } = req.body;
    User.findByIdAndUpdate(
        req.params.id,
        {
            $push : {
                flowers : { name, water_freq }
            }
        },
        { new: true }
    ).then((user) => res.json(user));
});

I want to delete flowers from users by their id but I'm unable to get it to work. 我想通过用户ID从用户中删除花朵,但无法使其正常工作。 The code below is my non-working attempt at it. 下面的代码是我无法正常工作的尝试。

router.delete('/:id/flowers/delete/:flowerid', (req, res) => {
    User.findByIdAndUpdate(req.params.id, {
        $pull : {
            flowers : { _id: req.params.flowerid }
        }
    }).then((user) => res.json(user));
});

I would greatly appreciate if someone can help me get this right. 如果有人可以帮助我解决这个问题,我将不胜感激。

One possible cause is, in your query {$pul: xxxx} , MongoDB is expecting a BSON type object id that was auto generated for each flower entry, while you are giving a string . 一个可能的原因是,在您的查询{$pul: xxxx} ,MongoDB期望在给定字符串时为每个花条目自动生成的BSON类型对象ID。 So you may want to convert it to the proper type before doing the query: 因此,您可能需要在执行查询之前将其转换为正确的类型:

try: 尝试:

 router.delete('/:id/flowers/delete/:flowerid', (req, res) => {
     User.findByIdAndUpdate(req.params.id, {
         $pull : {
             flowers : { _id: ObjectId(req.params.flowerid) }
         }
     }).then((user) => res.json(user)); });

To see more about the objectId 要了解有关objectId的更多信息

Thanks for the replies! 感谢您的答复! I did some more testing with postman and found out that in fact the code I posted in my question did work after all. 我对邮递员进行了更多测试,发现实际上我在问题中发布的代码确实有效。 What set me off was that the response with the user document still displayed the flower I had just deleted, which made me think it didn't work. 让我失望的是,用户文档的响应仍然显示我刚刚删除的花朵,这使我认为它不起作用。

I still have no idea why that is, or if there's a way to get a response with the updated user. 我仍然不知道为什么这样做,或者是否有办法获得更新后的用户的答复。 But the deletion seems to work as intended. 但是删除似乎按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM