【问题标题】:how do i delete array item in mongodb?如何删除 mongodb 中的数组项?
【发布时间】:2022-02-05 21:59:04
【问题描述】:

我想根据“noteID”的值从mongo db的项目架构内的note数组中删除一个元素。

项目架构

  endDate: {
    type: String,
    required: true,
    default: Date.now().toString()
  },
  notes: {
    type: [NoteSchema],
    required: false
  },
  users: [{
    type: String,
    required: false
  }]

笔记架构

const NoteSchema = mongoose.Schema({
  noteID: {
    type: String,
    require: true
  },
  title: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  endDate: {
    type: Date,
    default: Date.now()
  },
  priority: {
    type: String,
    default: "low"
  }
});

用express返回json

"endDate": "11.11.2021",
                "notes": [
                    {
                        "endDate": "2022-02-05T08:02:18.166Z",
                        "priority": "low",
                        "_id": "61fe2f423667ad054b62f84f",
                        "noteID": "cb978ec0-7229-4253-9e36-eaaf85b72ae3",
                        "title": "test note title",
                        "description": "test note desc"
                    },
                    {
                        "endDate": "2022-02-05T08:02:18.166Z",
                        "priority": "medium",
                        "_id": "61fe2f593667ad054b62f851",
                        "noteID": "760fda9f-e453-4e9c-bc9f-161f38fd29c0",
                        "title": "test note title 2",
                        "description": "test note desc 2"
                    }
                ],
                "users": [],

我想使用 noteID 从这个笔记目录中删除一个项目。

【问题讨论】:

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

通过 $pull 使用 update 以通过 noteID 从数组中删除元素:

  db.collection.update({},
 {
   $pull: {
      notes: {
        noteID: "cb978ec0-7229-4253-9e36-eaaf85b72ae3"
   }
  }
 })

解释:

上述查询将从对象数组 notes[] 中删除所有 nodeID 为“cb978ec0-7229-4253-9e36-eaaf85b72ae3”的对象。该操作适用于集合中找到的第一个文档。如果您需要应用到集合中的所有文档,则需要添加 { multi:true } 选项

playground

【讨论】:

    【解决方案2】:

    基本上你可以像猫鼬一样删除一个模式项。

    YourColletionName.findOneAndDelete({ noteID: "cb978ec0-7229-4253-9e36-eaaf85b72ae3" },
      function (err, data) {
    
        if (err){
          console.log(err)
        }
        else{
          console.log("Removed: ", data);
      }
    

    });

    如果您想使用页面上的 noteID 链接删除,您可以使用 req.params.noteID 而不是 cb978ec0-7229-4253-9e36-eaaf85b72ae3

    资源:

    【讨论】:

    • 不,这不能解决我的问题。您是否注意到 Notes 架构被添加为项目架构中的一种类型?
    猜你喜欢
    • 2013-06-08
    • 2018-02-17
    • 1970-01-01
    • 2013-06-02
    • 2016-02-25
    相关资源
    最近更新 更多