Home > Enterprise >  Delete all documents in a MongoDB collection via Django backend and Angular frontend
Delete all documents in a MongoDB collection via Django backend and Angular frontend

Time:12-20

I have managed to write code to add a customer to my MongoDB collection from my Angular service method to my Django http function, as follows:

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)

The POST method works fine and I can see the added document in my MongoDB Compass, but when I try to delete, I get:

DELETE http://localhost:8000/mydjangobaselink/ 500 (Internal Server Error)

All the posts and articles I have seen address communication issues in the browser, local host, etc... but given that my posting method works fine, I don't think that is my issue. Also, in Postman, I get Can not delete successfully!

Can anyone see what might be wrong that I cannot delete from database?

CodePudding user response:

Try with collection_name.delete_many({})

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

  • Related