简体   繁体   中英

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. 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. 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 . 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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