Mongodb对ObjectID的查询返回null

时间:2019-05-04 18:11:36

标签: javascript node.js mongodb express npm

以下方法应在sessionCollection中查询具有给定ObjectID的条目。

const mongodb = require('mongodb')
const ObjectID = mongodb.ObjectID


app.get('/getConversations', (req, res) => {
    verifyUser(req, res, function(result) {
        if(result !== "false") {
            for(var i=0; i<result.conversations.length; i++) {
                var objectid = new ObjectID(result.conversations[i].toString())
                conversationCollection.findOne({_id: objectid}, function(res2) {
                    console.log(res2.members)
                    res.end(res2)
                })
            }
        } else {
            res.end("Error")
        }
    })
})

结果对象具有例如以下数据:

{ 
  // ...
  conversations: [ 5ccdc51d22399918b45b33d4,
                   5ccdc52322399918b45b33d6 ],
  // ...
}

问题在于console.log(res2.members)总是抛出TypeError: Cannot read property 'members' of null。 findOne方法的接缝查询错误。我已经尝试了一些变体:

conversationCollection.findOne({"_id": objectid}, function(res2)
conversationCollection.findOne({_id: new ObjectID(result.conversations[i].toString())}, function(res2)
conversationCollection.findOne({"_id": ew ObjectID(result.conversations[i])}, function(res2)
conversationCollection.findOne({"_id": result.conversations[i]}, function(res2)

没有任何效果,每个变体都产生相同的nullpointer-exception。

1 个答案:

答案 0 :(得分:0)

这是因为res2保存的错误数据为空。 findOne函数在回调中有两个参数:第一个是错误,另一个是数据。他们两个都为空。

尝试一下:

app.get('/getConversations', (req, res) => {
    verifyUser(req, res, function(result) {
        if(result !== "false") {
            for(var i=0; i<result.conversations.length; i++) {
                var objectid = new ObjectID(result.conversations[i].toString())
                conversationCollection.findOne({_id: objectid}, function(err,res2) {
                    console.log(err)
                    console.log(res2.members)
                    res.end(res2)
                })
            }
        } else {
            res.end("Error")
        }
    })
})
相关问题