我的模型文档中有一个数组.我想根据我提供的密钥删除该数组中的元素,然后更新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();
});
});
};
Run Code Online (Sandbox Code Playgroud)
到目前为止,它找到了文档,但删除或保存工作.
Dan*_*nce 94
您也可以直接在MongoDB中进行更新,而无需加载文档并使用代码对其进行修改.使用$pull
或$pullAll
运算符从数组中删除项:
Favorite.update( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )
Run Code Online (Sandbox Code Playgroud)
http://docs.mongodb.org/manual/reference/operator/update/pullAll/
Jas*_*ing 43
已检查的答案确实有效,但最近在MongooseJS中正式使用,你应该使用pull.
doc.subdocs.push({ _id: 4815162342 }) // added
doc.subdocs.pull({ _id: 4815162342 }) // removed
Run Code Online (Sandbox Code Playgroud)
https://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-pull
我也只是看着那个.
请参阅Daniel的答案以获得正确的答案.好多了.
由于收藏夹是一个数组,您只需要将其拼接出来并保存文档.
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);
});
};
Run Code Online (Sandbox Code Playgroud)
小智 5
上面的答案显示了如何删除数组,以及如何从数组中拉出对象。
参考:https : //docs.mongodb.com/manual/reference/operator/update/pull/
db.survey.update( // select your doc in moongo
{ }, // your query, usually match by _id
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, // item(s) to match from array you want to pull/remove
{ multi: true } // set this to true if you want to remove multiple elements.
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
76693 次 |
最近记录: |