我有一个看起来有点像的模式:
var postSchema = new Schema({
created: { type: Date, default: Date.now },
updated: { type: Date, default: Date.now },
comments: { type: [Schema.ObjectId], ref: 'Comment' }
});
所以我的评论集合是引用我的评论架构/集合的对象 ID 的集合。
我需要在查询时删除其中一些,所以我正在尝试这样做:
var comments = [1, 2, 4];
Post.update({ _id: post_id}, {'$pullAll': {comments: comments }})
.exec(function(err) {
// How to remove documents with 1, 2, 4 ids from a Comment collection properly
});
执行上面的代码后,我从 Post.comments 中删除了评论的 ID,但我还需要从“评论”集合中删除这些评论。我应该怎么做?
编辑: 我怎样才能得到实际上没有被删除的文档的 ID。简单的例子:
Post.comments = [1, 2, 3];
Post.update({ _id: post_id}, {'$pullAll': {comments: [1,2]}});
在上面的代码中,Post.comments 只有 1,2,3,但我们试图提取 [1,2],所以我需要知道 id=3 在 Post.comments 中不存在,我不知道'需要将其从“评论”集合中删除。
最佳答案
使用 $in
运营商:
var comments = [1, 2, 4];
Post.update({ _id: post_id}, {'$pullAll': {comments: comments }})
.exec(function(err) {
Comment.remove({ _id: { $in: comments }}, function(err, numberRemoved) {
// The identified comments are now removed.
});
});
});
关于mongodb - Mongoose - 从 DBref 数组和项目本身中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12035721/