【问题标题】:How to remove an ObjectId from a ref array in a mongo schema?如何从 mongo 模式中的 ref 数组中删除 ObjectId?
【发布时间】:2019-06-25 21:38:29
【问题描述】:

我有这样的架构:

  var TestSchema = new Schema({
     name: String,
     ex: String,
     data:  [{type: Schema.ObjectId, ref: 'Data'}]
  });
  var Test = mongoose.model("Test", TestSchema);

它在 RoboT 中看起来像这样:

我想做的是按其 ID 删除数据。我正在这样做:

Test.update({}, {$pull: {data: idD }}, function(err, test) {
    if (err) {
        res.send(err);
    }
    res.send({
        success: true
    })
});

其中 idD 是我要删除的数据 ID。在此之前我只是做一个简单的

Data.deleteOne({_id: idD}, function...

它工作正常,但如果我刷新数据库,我的 idD 数据仍然存在于测试模式的数据数组中。 我也试过:

Test.update({}, {$pull: {data: {_id:idD }},
Test.update({}, {$pull: {data: {_id: mongoose.Types.ObjectId(idD)}}},

但没有任何效果。

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    更新多个文档时必须使用 multi: true。

     Test.update({}, {$pull: {data: idD },{multi: true}, function(err, test) {
            if (err) {
                res.send(err);
            }
            res.send({
                success: true
            })
        });
    

    【讨论】:

      【解决方案2】:

      您是否关闭了特定的收集窗口并再次打开它,或者您是否尝试重新连接机器人 3T 中的数据库?

      【讨论】:

      • 我刷新两个窗口,在数据收集中,我想要消除的数据消失了,但在测试文档的数据数组中它仍然存在
      • 同一个Id是否出现在多个集合中?如果是,则在选项中使用 { multi: true }。
      • 不是每个测试模式在它们的数组中都有不同的数据 ID
      • 不想我想问的是你想从数据数组中删除的同一个id出现在多个文档中吗?就像每个集合都有一个名为 Data 的数组一样,多个集合可能在它们的数据数组中包含相同的 id。对吗?
      猜你喜欢
      • 1970-01-01
      • 2017-11-04
      • 2021-04-01
      • 1970-01-01
      • 2016-10-04
      • 2013-01-26
      • 2017-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多