猫鼬findOne()函数未返回指定的项目

时间:2020-01-13 17:49:04

标签: javascript node.js mongodb express mongoose

我正在尝试使用javascript中的猫鼬来获取单个项目,但无法使其正常工作。该项目在我的数据库中的标题为“名称”,当我将.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
    }

1 个答案:

答案 0 :(得分:0)

您的代码有两个问题:

数量应为Number,而不是Int

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

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

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

这样,我在演出路线上得到了200