Node.js 猫鼬&x2B;NodeJS-尝试返回集合中的文档数时出错
我希望服务器发送产品集合中的文档数,但它会转到catch块。我一直在阅读mongoose文档,看起来我做得很正确,但是出现了一些问题。这是因为错误“无效状态代码”。您只需使用反勾号即可避免错误:Node.js 猫鼬&x2B;NodeJS-尝试返回集合中的文档数时出错,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我希望服务器发送产品集合中的文档数,但它会转到catch块。我一直在阅读mongoose文档,看起来我做得很正确,但是出现了一些问题。这是因为错误“无效状态代码”。您只需使用反勾号即可避免错误: const productSchema = new mongoose.Schema({ image: {type: String, required: true}, title: {type: String, required: true}, description: {type
const productSchema = new mongoose.Schema({
image: {type: String, required: true},
title: {type: String, required: true},
description: {type: String, required: true},
price: {type: Number, required: true, min: 0},
category: {type: String, required: true}
});
const Product = mongoose.model("Product", productSchema);
router.get("/", async(req, res) => {
try {
const products = await Product.find().countDocuments();
res.status(200).send(products)
}
catch(err) {
res.status(500).send("unexpected error occurred");
}
});
什么是错误,可以显示完全错误。请在catch块中添加一个
console.log
,以查看它抛出了什么错误。
router.get("/", async(req, res) => {
try {
const products = await Products.find().countDocuments();
res.status(200).send(`${products}`)
}
catch(err) {
res.status(500).send("unexpected error occurred");
}
});