gpt4 book ai didi

javascript - Mongodb 查询 ObjectID 返回 null

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:29 29 4
gpt4 key购买 nike

以下方法应在对话集合中查询具有给定 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)

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

最佳答案

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

关于javascript - Mongodb 查询 ObjectID 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55985498/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com