Mongoose删除文件中的数组元素并保存
我在模型文档中有一个数组。 我想根据我提供的密钥删除该数组中的元素,然后更新MongoDB。 这可能吗?
这是我的尝试:
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(); }); }); };
到目前为止,它find的文件,但删除或保存的作品。
您也可以在MongoDB中直接进行更新,而无需加载文档并使用代码进行修改。 使用$pull
或$pullAll
操作符从数组中删除项目:
Favorite.update( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )
http://docs.mongodb.org/manual/reference/operator/update/pullAll/
检查的答案确实工作,但在MongooseJS最新正式,你应该使用拉 。
doc.subdocs.push({ _id: 4815162342 }) // added doc.subdocs.pull({ _id: 4815162342 }) // removed
http://mongoosejs.com/docs/api.html#types_array_MongooseArray-pull
我也只是看着那个。
见但以理的答案是正确的答案。 好多了。
由于collections夹是一个数组,您只需将其拼接起来并保存文档即可。
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); }); };
这对我来说是非常有帮助的。
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 }) } }) });
我有一个名字是SubCategory
类别的模型,我想从这个类别数组中删除优惠券。 我有一个类别的数组,所以我使用了arrOfSubCategory
。 所以我用$in
操作符的帮助下,用map函数从这个数组中取出每个对象的数组。
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
如果你想使用...
你应该叫'use strict';
在你的js文件的顶部; 🙂