gpt4 book ai didi

node.js - Nodejs mongodb 在不应该返回空数组时返回空数组

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

我在mongodb User和Review中有2个集合,模式是User(_id,firstName,lastName,email,password)和Rev​​iew(_id,reviewForID,reviewdByID,reviewText),我有一个快速发布方法,我将使用它来返回用户以及与该用户关联的所有评论,但是当我尝试查询Review集合时,我有时会返回一个空数组。错误发生在 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 是一个 String 类型的字段,在该集合中存储的是 String 值,而在 User 集合中显然 _id 是 ObjectId 类型,因此您无法获取数据,因为存在类型不匹配。

当调用 toString 时,它基本上返回与 reviewForID 的 String 类型匹配的 String 值,这就是它与 toString 一起使用的原因。

也许您可以将 reviewForID 存储为 ObjectId 类型以进行直接匹配。

关于node.js - Nodejs mongodb 在不应该返回空数组时返回空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452485/

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