【问题标题】:Remove id from array of objects in mongodb从 mongodb 中的对象数组中删除 id
【发布时间】:2019-01-10 19:50:24
【问题描述】:

我尝试删除 ObjectId 数组中的 ObjectID。

我的模特:

let directoryCollection = new Schema(
  {
    email: { type: String },
    directory: [{
        name: { type: String },
        list: [ {type: Schema.ObjectId} ]
    }]
  },
  {collection: 'directory'}
);

我在 list 中有一个 ObjectID 数组。

我的数组中删除索引的代码:

let id = mongoose.Types.ObjectId(req.body.id);

directoryModel.update({'email': email, 'directory.name': oldDirectory}, {$pull: {'directory.list': id} }, function (req, result) {
    console.log(result);
    res.json('ok');
 });

但结果是:

{ ok: 0, n: 0, nModified: 0 }

Email 变量和 oldDirectory 变量是正确的。 我的ID是:5b5e5f34cfcd3906c8e6aa20

在我的数据库中相同:

有什么问题? 谢谢你!

【问题讨论】:

    标签: arrays mongodb mongoose mongodb-query objectid


    【解决方案1】:

    试试这个,将对象数组中$pull的语法更正

    directoryModel.update(
      { "email": email, "directory": { "$elemMatch": { "name": oldDirectory } } },
      { "$pull": { "directory.$.list": id } }
    })
    

    【讨论】:

    • 这行不通。它将拉整个 directory 而不是数组中的元素。他已经试过了。
    猜你喜欢
    • 2022-01-26
    • 2013-03-16
    • 2023-02-15
    • 2015-08-29
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多