【问题标题】:Delete all documents in a MongoDB collection via Django backend and Angular frontend通过 Django 后端和 Angular 前端删除 MongoDB 集合中的所有文档
【发布时间】:2022-01-19 14:44:13
【问题描述】:

我已设法编写代码,将客户从我的 Angular 服务方法添加到我的 MongoDB 集合到我的 Django http 函数,如下所示:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }),
  withCredentials: false
}

@Injectable()
export class MongoService {

  myApiBaseUrl = "http://localhost:8000/mydjangobaselink/";

  constructor(private httpClient: HttpClient) { }

  addCustomer(customerFormInfo: Customer): Observable<Customer> {
    return this.httpClient.post<Customer>(`${this.myApiBaseUrl}`, JSON.stringify(customerData), httpOptions);
  }

  deleteCustomer(): Observable<Customer> {
    return this.httpClient.delete<Customer>(`${this.myApiBaseUrl}`);
  }
}

@csrf_exempt
@api_view(['GET', 'POST', 'DELETE'])
def handle_customer(request):

    if request.method == 'POST':
        try:
            customer_data = JSONParser().parse(request)
            customer_serializer = CustomerModelSerializer(data=customer_data)
            if customer_serializer.is_valid():
                customer_serializer.save()

                # Write customer data to MongoDB.
                collection_name.insert_one(customer_serializer.data)

                response = {
                    'message': "Successfully uploaded a customer with id = %d" % customer_serializer.data.get('id'),
                    'customers': [customer_serializer.data],
                    'error': ""
                }
                return JsonResponse(response, status=status.HTTP_201_CREATED)
            else:
                error = {
                    'message': "Can not upload successfully!",
                    'customers': "[]",
                    'error': customer_serializer.errors
                }
                return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST)
        except:
            exceptionError = {
                'message': "Can not upload successfully!",
                'customers': "[]",
                'error': "Having an exception!"
            }
            return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'DELETE':
        try:
            CustomerModel.objects.all().delete()

            # Delete customer data from MongoDB.
            collection_name.deleteMany({})

            return HttpResponse(status=status.HTTP_204_NO_CONTENT)
        except:
            exceptionError = {
                'message': "Can not delete successfully!",
                'customers': "[]",
                'error': "Having an exception!"
            }
            return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

POST 方法工作正常,我可以在我的 MongoDB Compass 中看到添加的文档,但是当我尝试删除时,我得到:

删除 http://localhost:8000/mydjangobaselink/500(内部服务器错误)

我看到的所有帖子和文章都解决了浏览器、本地主机等中的通信问题……但鉴于我的发布方法运行良好,我认为这不是我的问题。另外,在 Postman 中,我得到 无法成功删除!

谁能看到我无法从数据库中删除的问题?

【问题讨论】:

    标签: django angular mongodb http django-rest-framework


    【解决方案1】:

    试试collection_name.delete_many({})

    https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.delete_many

    编辑:正如@NKSM 所指出的,有复制的文档:

    delete_many(filter, collat​​ion=None, hint=None, session=None)

    删除一个或多个匹配过滤器的文档:

    >>> db.test.count_documents({'x': 1})
    3
    >>> result = db.test.delete_many({'x': 1})
    >>> result.deleted_count
    3
    >>> db.test.count_documents({'x': 1})
    0
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • @Saigesp 它有效。谢谢你。我已将您的答案标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多