【问题标题】:Mongodb query for ObjectID returns null对 ObjectID 的 Mongodb 查询返回 null
【发布时间】:2019-09-22 22:14:08
【问题描述】:

以下方法应在 conversationCollection 中查询具有给定 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-method 接缝的查询是错误的。我已经尝试了一些变体:

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)

没有任何作用,每个变体都会产生相同的空指针异常。

【问题讨论】:

    标签: javascript node.js mongodb express npm


    【解决方案1】:

    这是因为 res2 保存了 null 的错误数据。 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")
            }
        })
    })
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2019-11-02
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      相关资源
      最近更新 更多