【问题标题】:Remove object from array with mongoose 5.12 ($pull not working)使用 mongoose 5.12 从数组中删除对象($pull 不起作用)
【发布时间】:2021-09-12 02:25:23
【问题描述】:

我对 mongoose 5.12 有疑问。

{
  "_id": {
    "$oid": "60db70c9956a6c4d0645d447"
  },
  "articles": [
    {
      "_id": {
        "$oid": "60db8764da322a23e787ca3d"
      },
      "type": "Déssert",
      "name": "dfd",
      "description": "",
      "price": 0,
      "tag": "",
      "picture": "noarticle.jpg"
    },
  ],
  "editor": 27,
}

我的餐厅文档包含文章(对象数组)

我想从中删除一篇文章。

我正在使用这个:

const deletedArticle = await this.restaurantModel.findOneAndUpdate(
  { editor: userId },
  { $pull: { articles: articleId } },
  { multi: true, new: true, useFindAndModify: true },
);

// userId -> 27 and articleId --> "60db8764da322a23e787ca3d"

但没有任何改变。

这是一个 _id 类型的问题吗?还是别的什么?

($push 选项有效)

【问题讨论】:

    标签: arrays object mongoose pull


    【解决方案1】:

    你做错了:

    { $pull: { articles: articleId } }
    

    应该是:

    { $pull: { articles: { _id : articleId } } }
    

    或者:

    { $pull: {"articles._id" : articleId } }
    

    【讨论】:

    • 这个方法我也试过了,但是不行
    • 但是当我添加一个 id 号码并按它过滤时,它是有效的。但问题是自动增量在 mongodb / mongoose 中不是原生的。
    • 在我看来,这是因为当我将 _id 添加到 axios 正文时,它会将其转换为字符串。但是我不知道怎么打回去
    • 使用 const newId = new mongoose.Types.ObjectId(_id)
    猜你喜欢
    • 2017-03-01
    • 2021-08-11
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多