【问题标题】:Delete an object from an array in Express Mongoose从 Express Mongoose 中的数组中删除对象
【发布时间】:2021-07-27 04:10:18
【问题描述】:
{
  "_id": "608c3d353f94ae40aff1dec4",
  "userId": "608425c08a3f8db8845bee84",
  "experiences": [
    {
      "designation": "Manager",
      "_id": "609197056bd0ea09eee9429c"
    },
    {
      "designation": "Asst. Manager",
      "_id": "608c530de8ade5221b0e6d4e"
    },
    {
      "designation": "Sr. Manager",
      "_id": "608c534be8ade5221b0e6d4f"
    },
  ]
}

我想删除 id 为 608c530de8ade5221b0e6d4e 的数组中的对象,这是我的代码,但这给了我错误。

这是控制器:

const userId = req.userData.userId;
const id = req.params.id;
    
Experience.findOneAndUpdate({ userId: userId }, { $pull: { 'experiences': { '_id': id } }}, { multi:true }, function(err, obj) {
                  //   //do something here
});

这是模型:

const newExpSchema = new mongoose.Schema({
  designation: { type: String,  default: ""},
});

const experienceSchema = new mongoose.Schema({
  userId: { type: String, required: true },
  experiences: [newExpSchema],
});

export default model("experience", experienceSchema);

我在 { $pull: { 'experiences': { '_id': id } }} 遇到错误 错误:

No overload matches this call.
Overload 1 of 3 .........
.......
The expected type comes from property '$pull' which is declared here on type 'UpdateQuery<Document<any, {}>>'

【问题讨论】:

    标签: node.js typescript express mongoose


    【解决方案1】:

    你能试试这个吗:

    Folder.findOneAndUpdate({
      "_id": "608c3d353f94ae40aff1dec4"
    },
    {
      $pull: {
        "experiences": {
          "_id": "608c530de8ade5221b0e6d4e"
        }
      }
    },
    {
      "multi": false
    })
    

    这是一个工作示例:https://mongoplayground.net/p/YtNGBTr52U9

    【讨论】:

    • 哦,对不起,这些数字只是举例,实际的字符串在那里。
    • 你能在工作示例中测试它吗?有用吗?
    • 没有重载匹配这个调用。使用您的解决方案后,我遇到了同样的错误。
    • 但它在我添加到问题的演示中有效,并且我使用了您问题中的相同数据。您可以将您的确切代码复制到问题中吗?
    • 我已经用真实数据和代码更新了这个问题。请看一下
    猜你喜欢
    • 2016-03-16
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2018-08-13
    • 2021-12-01
    • 2016-10-28
    相关资源
    最近更新 更多