我的架构看起来有点像:
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.com中删除了一条评论ID,但我还需要从“评论”集合中删除这些评论。我该怎么做?
编辑:如何获取实际未删除的文档ID。简单的例子:
Post.comments = [1, 2, 3];
Post.update({ _id: post_id}, {'$pullAll': {comments: [1,2]}});
在上面的代码中,Post.comments只有1,2,3,但我们试图拉[1,2],所以我需要知道在Post.comments中不存在id = 3而且我不喜欢不需要从'评论'集合中删除它。
答案 0 :(得分:1)
使用$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.
});
});
});
答案 1 :(得分:1)
您可以使用findAndModify命令发出更新,并在命令结果的value
属性中返回原始文档。将返回的comments
字段与$pullAll
查询中的ID进行比较,以确定哪些ID实际已被删除,您应该没有问题。
$ mongo
MongoDB shell version: 2.2.0-rc1
connecting to: test
> db.posts.drop()
true
> db.posts.insert({ _id: 1, comments: [1,2,3] })
> db.runCommand({
... findAndModify: "posts",
... query: { _id: 1 },
... update: { $pullAll: { comments: [1,2,4] }},
... })
{
"value" : {
"_id" : 1,
"comments" : [
1,
2,
3
]
},
"lastErrorObject" : {
"updatedExisting" : true,
"n" : 1
},
"ok" : 1
}
JohnnyHK在回答中提到,删除评论文档本身最好使用remove()
查询和$in
运算符。
注意:上面的示例使用Mongo JS shell。看起来Mongoose最近得到了findAndModify
的帮助方法(参见:PR #803),尽管你可以随时执行数据库命令,如果你使用的版本中没有这个命令。