Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I have an array in my model document. I want to delete some components in that array and want to update MongoDB. Is this achievable?

I am able to find that field but not able to replace or update

The following is my implementation:

var mongoose = require('mongoose'),

    Schema = mongoose.Schema;

var favorite = new Schema({

    cn: String,

    favorites: Array

});

module.exports = mongoose.model('Favorite', favorite, 'favorite');

exports.deleteFavorite = function (req, res, next) {

    if (req.params.callback !== null) {

        res.contentType = 'application/javascript';

    }

    Favorite.find({cn: req.params.name}, function (error, docs) {

        var records = {'records': docs};

        if (error) {

            process.stderr.write(error);

        }

        docs[0]._doc.favorites.remove({uid: req.params.deleteUid});

        Favorite.save(function (error, docs) {

            var records = {'records': docs};

            if (error) {

                process.stderr.write(error);

            }

            res.send(records);

            return next();

        });

    });

};

1 Answer

0 votes
by (107k points)

For deleting the items from the array, you can use the $pull or $pullAll operators, refer to the following code:

Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )

And one more thing you can simply update your mongodb without updating or making any change to the document that resides inside the mongodb database.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...