Mongoose delete array element in document and save

后端 未结 6 408
盖世英雄少女心
盖世英雄少女心 2020-11-28 23:53

I have an array in my model document. I would like to delete elements in that array based on a key I provide and then update MongoDB. Is this possible?

Here\'s my

6条回答
  •  有刺的猬
    2020-11-29 00:48

    Since favorites is an array, you just need to splice it off and save the document.

    var mongoose = require('mongoose'),
        Schema = mongoose.Schema;
    
    var favorite = new Schema({
        cn: String,
        favorites: Array
    });
    
    module.exports = mongoose.model('Favorite', favorite);
    
    exports.deleteFavorite = function (req, res, next) {
        if (req.params.callback !== null) {
            res.contentType = 'application/javascript';
        }
        // Changed to findOne instead of find to get a single document with the favorites.
        Favorite.findOne({cn: req.params.name}, function (error, doc) {
            if (error) {
                res.send(null, 500);
            } else if (doc) {
                var records = {'records': doc};
                // find the delete uid in the favorites array
                var idx = doc.favorites ? doc.favorites.indexOf(req.params.deleteUid) : -1;
                // is it valid?
                if (idx !== -1) {
                    // remove it from the array.
                    doc.favorites.splice(idx, 1);
                    // save the doc
                    doc.save(function(error) {
                        if (error) {
                            console.log(error);
                            res.send(null, 500);
                        } else {
                            // send the records
                            res.send(records);
                        }
                    });
                    // stop here, otherwise 404
                    return;
                }
            }
            // send 404 not found
            res.send(null, 404);
        });
    };
    

提交回复
热议问题