Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose delete array element in document and save

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 attempt:

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();         });     }); }; 

So far it finds the document but the remove nor save works.

like image 207
occasl Avatar asked Feb 08 '13 00:02

occasl


People also ask

How do you delete an element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

What does save () do in Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.


1 Answers

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

Favorite.updateOne({ cn: req.params.name }, {     $pullAll: {         favorites: req.params.deleteUid,     }, }); 

To remove objects from array then

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

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

like image 55
Daniel Flippance Avatar answered Sep 21 '22 09:09

Daniel Flippance