$pull 在 mongosh 中有效,但在 mongoose 中无效

$pull works in mongosh but not in mongoose

用户架构:

const UserSchema = new mongoose.Schema(
  {
    contacts: {
      type: Array,
      default: [],
    }
  }

);

module.exports = mongoose.model("User", UserSchema);

数据在mongodb

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id": ObjectId("61a7b499455e053ae4e4baeb"),
            "firstName":"Johnny",
            "lastName":"Cool",
            "occupation":"Programmer",
            "company":"Cool Comp."
        },

        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

此删除查询在 mongosh 中有效,联系人已从数据库中删除

db.users.updateOne(
  {'_id':ObjectId('6171fbcd85279d467c9b5be9')},
    {$pull: 
      {'contacts':
        {'_id': ObjectId('61a7b499455e053ae4e4baeb')}
      }
    }
)

结果数据看起来应该像这样:

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

但是,当我 运行 使用 npm 的 mongoose 库进行此查询时,命令“成功”但是联系人并未从数据库中删除。

User.updateOne(
  {'_id': mongoose.types.ObjectId('6171fbcd85279d467c9b5be9')},
    {$pull: 
      {'contacts':
        {'_id': mongoose.types.ObjectId('61a7b499455e053ae4e4baeb')}
      }
    }
)

结果数据如下所示

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id": ObjectId("61a7b499455e053ae4e4baeb"),
            "firstName":"Johnny",
            "lastName":"Cool",
            "occupation":"Programmer",
            "company":"Cool Comp."
        },

        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

而不是这个:

{
    "_id": ObjectId("6171fbcd85279d467c9b5be9"),
    "contacts":[
        {
            "_id":ObjectId("61a7b4be455e053ae4e4baec"),
            "firstName":"Evan",
            "lastName":"Evernost",
            "occupation":"Manager",
            "company":"Best Comp."
        }
    ]
}

不确定是什么问题。

因为 updateOne 是一个异步函数,所以只需要添加 await 关键字就可以了

await User.updateOne(
  {'_id': mongoose.types.ObjectId('6171fbcd85279d467c9b5be9')},
    {$pull: 
      {'contacts':
        {'_id': mongoose.types.ObjectId('61a7b499455e053ae4e4baeb')}
      }
    }
)