【问题标题】:Why does my Array.prototype.find() return undefined?为什么我的 Array.prototype.find() 返回未定义?
【发布时间】:2021-04-25 11:18:44
【问题描述】:

我有一个路由处理程序,我试图在其中查找用户的俱乐部对象集合,然后使用 Array.prototype.find() 查找特定的俱乐部对象。我不知道为什么它总是返回未定义。谁能看到我做错了什么?

router.get('/club', async (req,res) => {
    try {

        console.log(req.query.club); 
        // 6008d7537ea5c22b61dc616b
        
        const { clubs } = await User.findOne({ spotifyId: req.query.id }).populate('clubs').select('clubs');
        
        console.log(clubs); 
        // [{"_id":"6008d7537ea5c22b61dc616b","name":"asfasfs","description":"sdfasfa","privacy":"private","frequency":"bi-weekly","__v":0},{"_id":"6008ec8026900630c24fd533","name":"asfasfdsasf","description":"asdfasfdsf","privacy":"private","frequency":"monthly","__v":0}]
        
        let club = clubs.find(currentClub => (
           currentClub._id === req.query.club
        ));

        console.log(club)
        // undefined
        
        res.send(club)
    }
    catch {
        return res.status(400).send('No club found with given id')
    }
})

【问题讨论】:

  • 因为您有一个包含一个元素(索引 0)的数组,并且它是内部的一个对象。 .... 另外,我喜欢你评论数据结构,但如果那是一个字符串,你需要JSON.parse() 才能使用它。
  • 因为Mongoose ._ids are objects (尽管console.log 在此处将其显示为字符串)。 === 与字符串的比较总是会失败。你可以改用.id
  • 你为什么要使用Array 方法呢?只需Club.findById
  • @Bergi 我想我的想法是我想通过获取用户俱乐部的列表然后过滤来验证俱乐部是否属于用户。也许这没有必要?
  • @butthash3030 我可能会将所有者存储在俱乐部对象上然后验证这一点,或者尝试编写一个查询来检查 mongodb,这样我就不必加载所有俱乐部。但这可能是过早的优化,或者我过于关注关系数据库。

标签: javascript arrays mongoose


【解决方案1】:

_id 是一个对象

像这样更改你的代码

String(currentClub._id) === req.query.club

currentClub._id.toString() === req.query.club

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-04
    • 2017-07-23
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2021-10-19
    相关资源
    最近更新 更多