Node.js 无法读取属性';forEach&x27;将数据库id与用户请求的id进行比较时的未定义

Node.js 无法读取属性';forEach&x27;将数据库id与用户请求的id进行比较时的未定义,node.js,mongodb,express,Node.js,Mongodb,Express,我确实将数据插入了MongoDB数据库,现在我想将用户请求的id与存储在数据库中的id进行比较。使用forEach循环执行此操作时,得到的错误为TypeError:cannotread undefined的属性'forEach'。我在stack overflow中进行了搜索,但仍然无法找出问题所在。帮我解决这个问题 这是我的密码: app.get('/product/:id', (req, res) => { MongoClient.connect(url, { useNewUrl

我确实将数据插入了MongoDB数据库,现在我想将用户请求的id与存储在数据库中的id进行比较。使用forEach循环执行此操作时,得到的错误为TypeError:cannotread undefined的属性'forEach'。我在stack overflow中进行了搜索,但仍然无法找出问题所在。帮我解决这个问题

这是我的密码:

app.get('/product/:id', (req, res) => {
    MongoClient.connect(url, { useNewUrlParser: true }, (err, db) => {
        if (err) throw err;
        var dbo = db.db("product");
        var cursor = dbo.collection("details").find({}).toArray((err, result) => {
            if (err) throw err;
            cursor.forEach((_id)=>{
                if (_id == req.params.id) {

                return true;
                db.close();
                }
            })
            console.log(result);
        });

    });
});
我在数据库中存储的数据是:

[ { _id: '1', producttitle: 'Levis' } ]

您需要迭代结果变量,而不是游标 这是因为游标变量未定义,因为任务尚未完成

此外,您需要访问结果的_id:

result.forEach((currUser)=>{
            if (currUser._id == req.params.id) {

            return true;
            db.close();
            }
        })

如果您不介意使用async/await:

app.get('/product/:id', (req, res) => {
    MongoClient.connect(url, { useNewUrlParser: true }, async (err, db) => {
        if (err) throw err;
        var dbo = db.db("product");
        try{
            var results = await dbo.collection("details").find({}).toArray();
            results.forEach((product) => {
                if(product.id === req.params.id){
                    // do something you like here.
                    return true;
                    db.close();
                }
            });
        }catch(e){
            // error
        }
    });
});

顺便说一句,我想你应该
找到数据库中的所有文档,因为你还需要做其他事情。但是,如果没有,您应该将您的条件放入查询中,比如
dbo.collection(“details”).find({u id:req.params.id})

我认为您试图从数据库中获取唯一请求的记录,您可以直接查询,只获取那些不需要整个集合的记录。