Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 猫鼬&x2B;NodeJS-尝试返回集合中的文档数时出错_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js 猫鼬&x2B;NodeJS-尝试返回集合中的文档数时出错

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

我希望服务器发送产品集合中的文档数,但它会转到catch块。我一直在阅读mongoose文档,看起来我做得很正确,但是出现了一些问题。

这是因为错误“无效状态代码”。您只需使用反勾号即可避免错误:

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");
  }
});