Nodejs mongodb在不应该的时候返回空数组

我有2个在MongoDB用户和审查集合,模式是用户(_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 

因此,Review集合中的reviewForID看起来就是一个Stringtypes的字段,在该集合中,String值正在被存储,而在User集合_id中显然是ObjectIdtypes的,所以您不会获取数据,因为存在types不匹配。

当toString被调用的时候,它基本上会返回匹配reviewForID的Stringtypes的String值,这就是为什么它和toString一起工作的原因。

也许你可以存储reviewForID作为typesObjectId做一个直接的匹配。