我已經設法撰寫代碼將客戶添加到我的 MongoDB 集合中,從我的 Angular 服務方法到我的 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 中,我得到無法洗掉成功!
誰能看到我無法從資料庫中洗掉的問題?
uj5u.com熱心網友回復:
試試 collection_name.delete_many({})
https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.delete_many
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386131.html
