【发布时间】:2019-09-25 04:50:44
【问题描述】:
我正在尝试从 mongo db 中检索我的文档。
我向我的节点服务器发出 ajax get 请求,服务器应该根据“breed”变量找到文档,将其放入列表中并将其发送回客户端。
然后在ajax的成功部分,我要用列表填充一个listview。
问题是 find() 函数返回 null 我相信即使我的集合中有一个满足条件的文档。
这是我检索文档的方式:
function search(req,res){
var merr = mongoerr400(res)
var breed
if (req.params.query == "Foghorn")
breed={breed:"Foghorn"};
else if (req.params.query == "Hawk")
breed = {breed:"Hawk"};
else if (req.params.query == "Tweety")
breed = {breed:"Tweety"};
else if (req.params.query == "Little")
breed = {breed:"Little"};
else if (req.params.query == "Bertha")
breed = {breed:"Bertha"};
try{
mongo.coll(
'chicken',
function(coll){
coll.find(
{breed},
merr(function(cursor){
var list = []
cursor.each(merr(function(chicken){
console.log(chicken);
if( chicken ) {
var item = {
_id: chicken._id,
id: chicken.id,
dateTime: chicken.dateTime,
latitude: chicken.latitude,
longitude: chicken.longitude,
weight: chicken.weight,
eggs: chicken.eggs,
grain: chicken.grain,
category: chicken.category
}
list.push(item);
}
else {
common.sendjson(res,{ok:true,list:list})
}
}))
})
)
}
)
}
catch (err) {
console.log('Error writing to the file: ' + err.message)
res.sendStatus(500);
}
}
mongo.coll = function(name,win,fail){
mongo.db.collection(name,mongo.res(win,fail));
}
console.log(chicken) 在控制台中返回 null,因为它向我的客户端发送了一个 null 列表。
我在 mongodb 中的文档的 example。 知道为什么吗?
【问题讨论】:
-
find() 中的第一个参数不应该是像 {breed:"Hawk"} 这样的对象。你能尝试不带花括号传递“品种”吗?
-
@Krishna 太棒了。有用。我的错。我现在有一个新问题,它没有发送给客户端。
-
我已将其回复为“答案”,因此将来可能会遇到此问题的其他人将对答案有很好的了解。