【问题标题】:why is my mongoose findOne query returning more than one result为什么我的猫鼬 findOne 查询返回多个结果
【发布时间】:2020-02-03 20:44:54
【问题描述】:

我正在设置一条路线,以使用 findOne 和事物对象 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
    }

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

【问题讨论】:

  • 我不确定为什么你会得到“整个东西集合”,因为这对我来说听起来很疯狂,但是你有一个问题似乎很清楚,你需要将 req.params.id 转换为为您的查询工作的猫鼬 ObjectID 类型:new mongoose.Types.ObjectId(req.params.id)
  • 试过了,结果还是一样
  • 我认为还有其他事情发生,您如何调试这条路线?你确定这是你使用的路线吗? findOne 返回一个对象而不是数组,这是一个巨大的危险信号,表明某些事情没有按照您的预期方式工作。
  • @tomslabbaert 我试过这个并得到了同样的东西集合:` app.get("/api/stuff/:id",(req, res, next)=>` {res.status(200).json(thing);});跨度>
  • 您是在调试服务器端还是只查看响应?您是否有其他路线正在匹配?

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 2023-03-26
    • 2021-09-18
    • 2020-05-04
    • 2019-01-26
    • 2019-03-25
    • 2019-02-13
    相关资源
    最近更新 更多