MongoDB查询Objectid返回null



以下方法应在"对话"中查询给定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。

这是因为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")
        }
    })
})

最新更新