【问题标题】:How can I write conditional logic with the returned value from mongoose db.collection.find()?如何使用 mongoose db.collection.find() 的返回值编写条件逻辑?
【发布时间】:2019-04-13 14:53:22
【问题描述】:

晚上好 Stack Overflow,

我正在处理一个个人项目,我试图弄清楚为什么我无法从我的后端 API 获得正确的响应。您将在下面找到我正在编写的其中一条路线的代码。在这里,我试图通过其奥秘字段从数据库中获取角色。

我的想法是,如果 mongoose 方法 find() 未能找到具有给定奥秘的角色,那么我应该返回 404 错误并发回详细说明问题所在的 json 响应。

我想我可以通过说 if(!personas) 来做到这一点,其中角色是 mongoose db.collection.find() 返回的内容。这不起作用,我的 API 返回具有 200 OK 状态的空方括号。我所有的测试都是通过 Postman 完成的。

代码中的console.logs是我的调试语句。

console.log(personas === {} ? true : false);返回错误

console.log(角色类型);返回对象

console.log(personas === [] ? true : false);返回错误

console.log(personas === undefined ? true : false);返回错误

router.get("/personas/by/:arcana", (req, res) => {
const errors = {};
// The below logic is not working. We're not sending a 404 on failure.
Persona.find({ arcana: req.params.arcana })
.then(personas => {
  console.log(personas === {} ? true : false);
  console.log("What is the type of the personas variable?",typeof personas);
  console.log(personas === [] ? true : false);
  if (!personas) {
    errors.no_personas =
      "There are no personas in the compendium with that arcana.";
    return res.status(404).json(errors);
  }
  res.json(personas);
})
.catch(err => res.status(404).json({ personas: "There are no personas." }));
});

如何编写我的逻辑以便从后端返回正确的状态码?

【问题讨论】:

  • 您不能使用 '===' 将 2 个对象或数组等同起来。如果您比较指向同一对象的 2 个变量,您只会得到正确的结果:const obj1 = {test: '1'}; const obj2 = obj1; obj1 === obj2 返回 true;

标签: javascript express mongoose ecmascript-6 es6-promise


【解决方案1】:

if (!personas.length)if (personas.length === 0)。如果personas是空数组或对象,则不是假的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-02
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多