【问题标题】:fetch pictures with mongoose with a certain parameter使用特定参数获取带有猫鼬的图片
【发布时间】:2021-08-04 08:13:22
【问题描述】:

您好,感谢所有愿意并准备帮助我的人!

我有一个像这样的猫鼬模型:

const pictureSchema = mongoose.Schema ({
    pictureName : String,
    creator : String,
    description : String,
    img : String,
    createdAt : {
        type : Date,
        default : new Date(),
    },
    themeLinked : String
    
})

现在我要做的是获取所有具有“themeLinked”特定值的文档。这就像对我的文档中具有相同“themeLinked”的所有条目进行排序。

所以我做了什么,从我的前端反应应用程序,我发送了作为 req.param 链接的主题的值。所以它通过 GET 请求发送到我的后端。

在我的后端,在控制器中我写了这段代码:

const fetchPictures = async (req,res) => {
    const  {themeId} = req.params;
    try {

        const pictures = await pictureModel.findOne({themeLinked : themeId});
        res.status(200).json(pictures)

    } catch (err) {
        res.status(404).json({ message : err})
    }
}

在我的 chrome 浏览器的网络选项卡中,我得到 'null' 作为 Response 的值。

作为一个初学者,我正在努力寻找正确的方法来获取所有具有相同“themeLinked”值的图片......这一定很简单,但我正在努力

谢谢!!

【问题讨论】:

    标签: express mongoose axios


    【解决方案1】:

    好的,我知道了,我需要做的就是:

    const fetchPictures = async (req,res) => {
        const  {themeId} = req.params;
        try {
    
            const pictures = await pictureModel.find({themeLinked : themeId});
            res.status(200).json(pictures)
    
        } catch (err) {
            res.status(404).json({ message : err})
        }
    }
    

    由于明显的词法原因,findOne 只返回一个条目,因为 find 返回具有相同匹配 'themeLinked' 值的所有条目......:)

    【讨论】:

      猜你喜欢
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2016-11-12
      • 2017-12-31
      • 2020-03-10
      • 2015-11-27
      • 2014-09-10
      相关资源
      最近更新 更多