【问题标题】:Mongoose - remove items from DBref array and item itselfMongoose - 从 DBref 数组和项目本身中删除项目
【发布时间】:2012-08-20 23:44:04
【问题描述】:

我有一个看起来有点像的架构:

var postSchema = new Schema({
   created: { type: Date, default: Date.now },
   updated: { type: Date, default: Date.now },
   comments: { type: [Schema.ObjectId], ref: 'Comment' }
});

所以我的 cmets 集合是引用我的评论模式/集合的对象 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.cmets 中删除了评论的 id,但我还需要从“评论”集合中删除这些 cmets。我该怎么做?

编辑:我怎样才能得到实际上没有被删除的文档的 ID。简单的例子:

Post.comments = [1, 2, 3]; 
Post.update({ _id: post_id}, {'$pullAll': {comments: [1,2]}});

在上面的代码中 Post.cmets 只有 1,2,3,但我们试图拉 [1,2],所以我需要知道 Post.cmets 中不存在 id=3 而我不知道'不需要从'评论'集合中删除它。

【问题讨论】:

    标签: mongodb express mongoose


    【解决方案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.
        });
      });
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用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),尽管如果您使用的版本中没有该数据库命令,您始终可以执行该命令。

      【讨论】:

        猜你喜欢
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 2021-10-03
        • 2014-09-21
        • 2014-09-03
        • 1970-01-01
        • 2014-08-08
        • 1970-01-01
        相关资源
        最近更新 更多