mongoose Mongodb删除子数组中的元素

7tofc5zh  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(156)

我的问题是如何移除数组中具有指定id的元素。
数据库结构:

const userScheme = new mongoose.Schema({
    login: String, password: String, surveys: [{
        _id: mongoose.Schema.ObjectId, inquirer: [
            {
                _id: mongoose.Schema.ObjectId,
                question: String,
                answers: [String]
            }
        ]
    }], statistics: [
        {
            _inquirerId: mongoose.Schema.ObjectId, surveyAnswers: [Number]
        }
    ]
});

调查栏目:

[
  {
    "_id": new
    ObjectId(
    "63692b8dda87c344d03dae3d"
    ),
    "inquirer": [
      {
        "_id": new
        ObjectId(
        "63692b8dda87c344d03dae39"
        ),
        "question": "Question 4",
        "answers": [
          "option 1",
          "option 2",
          "option 3"
        ]
      },
      {
        "_id": new
        ObjectId(
        "63692b8dda87c344d03dae3a"
        ),
        "question": "Question 5",
        "answers": [
          "option 1",
          "option 2",
          "option 3"
        ]
      },
      {
        "_id": new
        ObjectId(
        "63692b8dda87c344d03dae3b"
        ),
        "question": "Question 6",
        "answers": [
          "option 1",
          "option 2",
          "option 3"
        ]
      }
    ]
  }
]

我正在尝试按ID从查询者中删除问题6

db.users.updateOne({"surveys.inquirer._id": ObjectId("63692b8dda87c344d03dae39")},
{$pull: {"surveys.inquirer": {"_id": ObjectId("63692b8dda87c344d03dae39")}}});

此代码不工作。我还需要更新一个问题和答案:

db.users.findOneAndUpdate({
"surveys.inquirer._id": ObjectId("63692b8dda87c344d03dae39"),
}, { $set: {
"surveys.$.inquirer.question": "new question",
"surveys.$.inquirer.answers": ["one", "two", "three"]
}});

这种方法也行不通,我做错了什么吗?
我尝试了代码,我提供的问题,但它不工作

5sxhfpxr

5sxhfpxr1#

正在更新:

db.users.updateOne({}, {
            $set: {
                "surveys.$[surveys].inquirer.$[inquirer].question": "Test new String",
                "surveys.$[surveys].inquirer.$[inquirer].answers": ['1', '2', '3']
            }
        }, {
            arrayFilters: [{
                "surveys._id": ObjectId("63692b8dda87c344d03dae3d")
            }, {
                "inquirer._id": ObjectId("63692b8dda87c344d03dae39")
            }]
        })

按id删除:

db.users.updateOne({}, {
    $pull: {
        "surveys.$[surveys].inquirer": {
            "_id": ObjectId("63692b8dda87c344d03dae3a")
        }
    }
}, {
    arrayFilters: [{
        "surveys._id": ObjectId("63692b8dda87c344d03dae3d")
    }]
})

相关问题