Mangosta eliminar elemento de matriz en el documento y guardar
Tengo un array en mi documento modelo. Me gustaría eliminar elementos de esa matriz en función de una clave que proporcione y luego actualizar MongoDB. Es esto posible?
Aquí está mi intento:
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();
});
});
};
Hasta ahora encuentra el documento pero el remove nor save funciona.
5 answers
También puede hacer la actualización directamente en MongoDB sin tener que cargar el documento y modificarlo usando código. Utilice los operadores $pull
o $pullAll
para eliminar el elemento de la matriz:
Favorite.update( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )
Http://docs.mongodb.org/manual/reference/operator/update/pullAll /
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-13 08:01:32
La respuesta marcada funciona, pero oficialmente en MongooseJS latest, debe usar pull.
doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed
Http://mongoosejs.com/docs/api.html#types_array_MongooseArray-pull
Yo también estaba buscando eso.
Ver la respuesta de Daniel para la respuesta correcta. Mucho mejor.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-08 20:29:32
Dado que favoritos es una matriz, solo necesita empalmar y guardar el documento.
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);
});
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-26 23:37:57
Esto está funcionando para mí y realmente muy útil.
SubCategory.update({ _id: { $in:
arrOfSubCategory.map(function (obj) {
return mongoose.Types.ObjectId(obj);
})
} },
{
$pull: {
coupon: couponId,
}
}, { multi: true }, function (err, numberAffected) {
if(err) {
return callback({
error:err
})
}
})
});
Tengo un modelo cuyo nombre es SubCategory
y quiero eliminar el cupón de esta matriz de categoría. Tengo un array de categorías así que he usado arrOfSubCategory
. Así que obtengo cada matriz de objeto de esta matriz con función de mapa con la ayuda del operador $in
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-24 05:01:28
keywords = [1,2,3,4];
doc.array.pull(1) //this remove one item from a array
doc.array.pull(...keywords) // this remove multiple items in a array
Si quieres usar ...
debes llamar a 'use strict';
en la parte superior de tu archivo js;:)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-06 04:58:18