尝试创建一个API,我们可以使用CRUD选项。事情是我们的删除功能dosnt工作,当我们点击删除发布网站崩溃。
(填写信息导致stackoverflow不会让我发布这个愚蠢的事情。)
var mongoose = require('mongoose');
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
mongoose.connect("mongodb://localhost/shop");
var Schema = mongoose.Schema;
var productSchema = new Schema({
id: String,
name: String,
description: String,
origin: String,
categories: [{type: Schema.Types.ObjectId, ref: "Category"}]
}, {collection: 'product'});
var categorySchema = new Schema({
_id: Schema.Types.ObjectId,
name: String,
description: String,
products: [{type: Schema.Types.ObjectId, ref: "Product"}]
}, {collection: 'category'});
var personSchema = new Schema({
_id: Schema.Types.ObjectId,
name: String,
email: String,
phone: String
}, {collection: 'person'});
var listSchema = new Schema({
_id: Schema.Types.ObjectId,
name: String,
date: String,
product: [String]
}, {collection: 'list'});
var Product = mongoose.model('Product', productSchema);
var Category = mongoose.model('Category', categorySchema);
var Person = mongoose.model('Person', personSchema);
var List = mongoose.model('List', listSchema);
var app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/* Get */
app.get('/', function(req,res){
Product.find({}, '', function(error, product){
Person.find({},'', function(error, person){
Category.find({},'', function(error, category){
List.find({},'', function(error, list){
res.json({
Product: product,
Person: person,
Category: category,
List: list
});
});
});
});
});
});
app.post("/product", function(req, res) {
var newItem = new Product (req.body);
newItem.save()
.then (function(product) {
Category.findByIdAndUpdate(
req.body.categories, { $push: {"products": product._id }}, { new: true }, function (err, product) {
res.send(product);
})
.catch (function(err) {
res.status(400).send("unable to add item to db");
});
});
});
app.get('/all', function(req,res){
Category.
find({}).
populate("products").
exec(function (err, product) {
res.json(product);
});
});
app.get('/category/:id', function(req,res){
Category.
find({_id: mongoose.Types.ObjectId(req.params.id)}).
populate("products").
exec(function (err, product) {
res.json(product);
});
});
app.get('/category/1', function(req,res){
Category.
find({name: "grönsaker"}).
populate("products").
exec(function (err, product) {
res.json(product);
});
});
app.get('/category/2', function(req,res){
Category.
find({name: "mejeri"}).
populate("products").
exec(function (err, product) {
res.json(product);
});
});
app.put('/product/:id', function(req, res) {
Product.findByIdAndUpdate(req.params.id, { $set: req.body }, { new: true }, function (err, product) {
if (err) return handleError(err);
res.send(product);
});
});
/
app.delete('/product', function (req, res) {
Category.findById(req.body._id, function (err, product) {
var cat_id = Product.categories [0]
Category.findByIdAndUpdate(cat_id, { $pull: {products: req.body._id}}, function(err, product){
product.remove();
});
});
});
app.listen(3000);
我们知道SendDeleteRequest的ID有问题,但我们不知道应该写什么。
<!DOCTYPE html>
<html>
<head>
<title>Express.js client</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function sendGetRequest() {
var data = { id: 123 };
$.ajax({
url: "http://localhost:3000/all",
type: "GET",
data: data,
success: response => $("#response").text(JSON.stringify(response))
});
}
function sendGetGronsaker() {
var data = { id: "5a1696d69759edba95fa4b18" };
$.ajax({
url: "http://localhost:3000/category/5a1696d69759edba95fa4b18",
type: "GET",
data: data,
success: response => $("#response").text(JSON.stringify(response))
});
}
function sendGetMejeri() {
var data = { id: "5a1696d69759edba95fa4b17" };
$.ajax({
url: "http://localhost:3000/category/5a1696d69759edba95fa4b17",
type: "GET",
data: data,
success: response => $("#response").text(JSON.stringify(response))
});
}
/* function sendGetGronsaker() {
var data = { id: "5a1696d69759edba95fa4b18" };
$.ajax({
url: "http://localhost:3000/category/5a1696d69759edba95fa4b18",
type: "GET",
data: data,
success: response => $("#response").text(JSON.stringify(response))
});
} */
function sendPostRequest() {
var data = { name: "majs", description: "Majs är gott", origin: "spain", categories: "5a1696d69759edba95fa4b18" };
$.ajax({
url: "http://localhost:3000/product",
type: "POST",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: response => $("#response").text(JSON.stringify(response))
});
}
function sendPutRequest() {
var data = { origin: "spain" };
$.ajax({
url: "http://localhost:3000/product/5a1696d79759edba95fa4b20",
type: "PUT",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: response => $("#response").text(JSON.stringify(response))
});
}
function sendDeleteRequest() {
var data = { id: 789 };
$.ajax({
url: "http://localhost:3000/product",
type: "DELETE",
data: data,
success: response => $("#response").text(response)
});
}
</script>
<style type="text/css">
#output {
margin-bottom: 3ex;
}
#label {
font-weight: bold;
}
</style>
</head>
<body>
<div id="output">
<span id="label">Server response:</span>
<span id="response"></span>
</div>
<div>
<button onclick="sendGetMejeri()">GET Mejeri</button>
<button onclick="sendGetGronsaker()">GET Gronsaker</button>
<button onclick="sendGetRequest()">GET All</button>
<button onclick="sendPostRequest()">Send POST request</button>
<button onclick="sendPutRequest()">Send tomat PUT request</button>
<button onclick="sendDeleteRequest()">Send DELETE request</button>
</div>
</body>
</html>
答案 0 :(得分:0)
您正在传递没有下划线字符的id参数
只需将req.body。 _id 更改为req.body。 id
app.delete('/product', function (req, res) {
Category.findById(req.body.id, function (err, product) {
var cat_id = Product.categories [0]
Category.findByIdAndUpdate(cat_id, { $pull: {products: req.body.id}}, function(err, product){
product.remove();
});
});
});