【发布时间】: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