为什么我的猫鼬findOne查询返回多个结果

时间:2019-10-06 05:47:24

标签: javascript node.js mongodb mongoose mongodb-query

我正在设置一条路线,使用findOne和Thing对象ID作为参数,从事物集合中返回特定事物。为什么结果不只返回一个匹配的东西?

我尝试使用id作为参数的findOne

这是事物模式

const mongoose = require("mongoose");
const thingSchema = mongoose.Schema({
title: { type: String, required: true },
description: { type: String, required: true },
imageUrl: { type: String, required: true },
userId: { type: String, required: true },
price: { type: Number, required: true }
});
module.exports = mongoose.model("Thing", thingSchema);

查找事物路线

  app.get("/api/stuff/:id", (req, res, next) => {
  Thing.findOne({
    _id: req.params.id
  })
    .then(thing => {
      res.status(200).json(thing);
    })
    .catch(error => {
      res.status(404).json({
        error: error
      });
    });
});

我希望/api/stuff/:5d9834968e23a32580a1751b的结果是:

 {
        "_id": "5d9834968e23a32580a1751b",
        "title": "tecno camon 8",
        "description": "quality condition",
        "imageUrl": "https://i0.wp.com/www.techslize.com/wp-content    /uploads/2017/02/Tecno-camon-c8-black.png?resize=407%2C450&ssl=1",
        "price": 3000,
        "userId": "userID40282382",
        "__v": 0
    }

但是实际结果是整个事物的集合。

1 个答案:

答案 0 :(得分:0)

req.params来自URL的路径段,该路径段与路由定义中的参数(例如/api/stuff/:id)匹配。因此,使用使用该名称的路由和URL,例如/api/stuff/5d9834968e23a32580a1751b,然后是_id: req.params.id

从网址:删除/api/stuff/:5d9834968e23a32580a1751b并发送此网址/api/stuff/5d9834968e23a32580a1751b