【问题标题】:Can't access details of mongoose find() result无法访问 mongoose find() 结果的详细信息
【发布时间】:2014-01-24 19:41:06
【问题描述】:

在 MongoDB 中使用 Node/Express,我试图查找是否存在具有特定字段名称的对象。

我认为数据库连接本身没问题,因为我可以很好地将东西添加到数据库中(通过运行应用程序然后通过 mongo shell 检查来确认)

以下代码应该将 Class 的字段 student 增加 1,如果我遇到问题,则继续到下一页 /nextpage

exports.join = function(req,res,next){
 Class.find(({code:{$in: [req.body.roomNumber]}}), function(err, out){
  if(err){res.redirect('/'); next(err);}
  else{
   console.log(out);                 // returns the whole object from db. 
                                     // for no match, I get "[]"
   console.log(req.body.formEntry);  // returns the entered form value OK
   console.log(out.roomNumber);      // always returns "undefined"; why?
   if(out != null) {                 // always passes
    console.log('adding 1 to students');
    Class.update({code:req.body.formEntry}, {$inc:{'students':1}}); // also didn't work
    res.redirect('/nextpage');
   }else{
   console.log('class not found');
   }
  }
 };
}

我尝试过检查out.params.roomNumber(未定义)或out.next()(认为这是一个查询)之类的内容,但考虑到@ 987654329@ 给了我我想要的对象,它的所有字段都完好无损。我读了一个类似的问题,但问题在于异步性,因为整个事情都在回调中,我认为可能并非如此。

【问题讨论】:

  • 您永远不会执行更新查询。
  • 更多信息请见this answer
  • 啊,那是我必须忽略的另一个细节。谢谢。

标签: node.js mongodb mongoose


【解决方案1】:

find 返回一个结果数组,所以out 是一个数组。

如果每个班级都有唯一的房间号,使用findOne 更有意义:

Class.findOne({ code : req.body.roomNumber }, function(err, out) {
  // `out` is now a single result, provided there was a match
  ...
});

另外,使用$in 匹配单个房间号有点多余,所以我将其排除在查询之外(类似于您用于update 的查询)。

顺便说一句,您不应该将res.redirect()next() 混合在一起(因为发送重定向会结束请求,但next 会将其传递给其他处理程序,这将在 Express 中触发错误)。我建议使用这个:

if (err) {
  return res.redirect('/');
}

【讨论】:

  • findOne 运行良好,谢谢。编辑:并指出重定向+下一个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-31
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多