gpt4 book ai didi

javascript - mongoose findOne() 函数不返回指定的项目

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:49 25 4
gpt4 key购买 nike

我试图在 javascript 中使用 mongoose 获取单个项目,但无法使其工作。该项目在我的数据库中的标题为“名称”,当我将 .get 与/products 一起使用时,它工作正常。我所有获得所有项目的方法都效果很好,我只是在处理单个项目时遇到了麻烦。任何帮助是极大的赞赏。谢谢!

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
extend: true
}));

app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/ShoppingCartDB", {useNewUrlParser: true});

const productSchema = {
name: String,
price: String,
quantity: Int
};

const Products = mongoose.model("Products", productSchema);
//sets route to all items in products database
app.route("/products")
//gets ALL items in cart
.get(function (req, res) {
Products.find(function(err, foundProducts) {
console.log(foundProducts);
if (!err) {
res.send(foundProducts);
} else {
res.send(err);
}
});
})
//deletes ALL items in cart
.delete(function(req, res) {
Products.deleteMany(function(err) {
if (!err) {
res.send("All products removed from shopping cart");
} else {
res.send(err);
}
})
});
//changes route to single item based on name
app.route("/products/:itemName")

.get(function(req, res) {
Products.findOne({name: req.params.itemName}, function(err, foundItem){
if (foundItem) {
res.send(foundItem);
} else {
res.send(err);
}
});
})

.delete(function(req, res) {
Products.deleteOne(
{name: req.params.itemName},function(err) {
if (!err) {
res.send("Success");
} else {
res.send(err);
}
}
);
});




app.listen(3000, function() {
console.log("Server is running on port 3000");
});

我的数据库:

{
"_id": "5e1ca39ef94f6e20827ee890",
"name": "orange",
"price": "0.99",
"quantity": 1
},
{
"_id": "5e1ca39ef94f6e20827ee893",
"name": "apple",
"price": "1.5",
"quantity": 2
},
{
"_id": "5e1ca39ef94f6e20827ee896",
"name": "bread",
"price": "3.99",
"quantity": 1
},
{
"_id": "5e1ca39ef94f6e20827ee899",
"name": "milk",
"price": "4.99",
"quantity": 3
},
{
"_id": "5e1ca39ef94f6e20827ee89c",
"name": "coffee",
"price": "4.99",
"quantity": 2
}

最佳答案

您的代码有两个问题:

数量应该是Number,而不是Int:

const productSchema = {
name: String,
price: String,
quantity: Number
};

extend: true 不是 bodyParser 上的 extend: true:

app.use(
bodyParser.urlencoded({
extended: true
})
);

这样我就可以在演出路线上获得200

关于javascript - mongoose findOne() 函数不返回指定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59721587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com