【发布时间】:2017-05-18 01:48:01
【问题描述】:
我在 mongodb 用户和评论中有 2 个集合,模式是用户(_id,名字,姓氏,电子邮件,密码)和评论(_id,reviewForID,reviewdByID,reviewText),我有一个我将使用的快递方法返回用户和与该用户关联的所有评论,但是当我尝试查询评论集合时,有时会返回一个空数组。错误发生在 getReviews() 函数中,我已经注释了导致错误的行。我不知道是什么导致了错误以及为什么它只在我添加 toString() 时才起作用
注意:getReview() 函数的目的是从数据库中获取所有评论的数组,并将该数组附加到 userA 对象,然后将 userA 对象作为响应发送给客户端
var ObjectId = require('mongodb').ObjectID; //used to query objs by id
//parameters are (userid)
app.post('/getUserInfo', function (req, res)
{
var queryObj = { _id: new ObjectId(req.body.userid)};
MongoClient.connect(url, function (err, db)
{
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else //HURRAY!! We are connected. :)
{
var collection = db.collection('User');
collection.findOne(queryObj, function (err, resultDocument)
{
if (err)
{
console.log(err);
}
else if (resultDocument)
{
getReviews(resultDocument,res);
}
else
{
res.send({"result":"failed"});
}
db.close();//Close connection
});//collection.find end
}//else
});//MongoClient.connect end
});//get user info end
//find all the reviews and add them to the object userA
function getReviews(userA,response)
{
//var queryObj = { reviewForID: userA._id }; returns empty array
//var queryObj = { reviewForID: new ObjectId(userA._id) }; returns empty array
//var queryObj = { reviewForID: userA._id.toString() }; returns correct documents
MongoClient.connect(url, function (err, db)
{
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
}
else //HURRAY!! We are connected. :)
{
var collection = db.collection('Review');
collection.find(queryObj).toArray(function (err, result)
{
if (err)
{
console.log(err);
}
else
{
response.send(result);
}
db.close();//Close connection
});//coolection.find end
}//else
});//MongoClient.connect end
}//get reviews end
【问题讨论】: