mongodb - Mongoose - 从 DBref 数组和项目本身中删除项目

标签 mongodb express mongoose

我有一个看起来有点像的模式:

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/

相关文章:

php - 使用 YiiMongoDbSuite 删除数组元素

javascript - 捕获异常 : Error: write after end after upgrading Node version

node.js - 如何将nodejs和express设置为 digital ocean 上的docker容器?

node.js - 请求的资源上不存在 'Access-Control-Allow-Origin' header

javascript - Node 中带有 Mongoose 和 Promise 的奇怪异步行为

python - MongoDB:找到数组中的最小元素并将其删除

mongodb - MongoDB 中的 Golang 嵌套对象

javascript - 我可以在 Meteor 查找函数中使用用户定义的正则表达式而不转义特殊字符吗?

node.js - findByIdAndUpdate 的一致预保存验证

node.js - Mongoose聚合错误: Arguments must be aggregate pipeline operators