Reputation: 111
i have 2 collections in mongodb User and Review, the schemas are User(_id,firstName,lastName,email,password) and Review(_id, reviewForID,reviewdByID,reviewText), i have an express post method that i will use to return the User and all the reviews associated with that user, but when i try to query the Review collection i sometimes get an empty array returned. the error occurs in the getReviews() function, i have commented the line causeing the error. i do not know what is causeing the error and why it only works when i add toString()
note: the purpose of the getReview() function is to get the array of all the reviews from the db and append that array to the userA object then send the userA object as a response to the client
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
Upvotes: 2
Views: 1324
Reputation: 2831
So looks like reviewForID in Review collection is a field of type String, In that collection String value is being stored whereas clearly in User collection _id is of type ObjectId, so you don't get the data because there is a type mismatch.
when toString is called, it basically returns the String value which matches the String type of reviewForID, that's why it works with toString.
maybe you can store reviewForID as type ObjectId to make a direct match.
Upvotes: 1