本文介绍了猫鼬删除文档中的数组元素并保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的模型文档中有一个数组.我想根据我提供的密钥删除该数组中的元素,然后更新MongoDB.这可能吗?
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?
这是我的尝试:
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.
推荐答案
您也可以直接在MongoDB中进行更新,而不必加载文档并使用代码对其进行修改.使用$pull
或$pullAll
运算符从数组中删除该项:
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: {uid: [req.params.deleteUid] } } )
(您也可以将updateMany用于多个文档)
(you can also use updateMany for multiple documents)
http://docs.mongodb.org/manual/reference/operator /update/pullAll/
这篇关于猫鼬删除文档中的数组元素并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!