【问题标题】:How can i get and display all value without undefined value from mongodb?如何从 mongodb 获取和显示没有未定义值的所有值?
【发布时间】:2021-08-20 07:44:52
【问题描述】:

如何从 mongodb 获取和显示没有未定义值的所有值?

app.post('/add_teacher',(req,res)=>{
    const name = req.body.name;
    const biography = req.body.biography;
  teacherCollection.insertOne({name,biography})
         .then(result =>{
           console.log(result);
             res.send(result.insertedCount>0);            
        })                  
    }) 

app.get('/get_all_teacher', (req, res) =>{

  teacherCollection.find()
  .toArray((err, course) =>{
   res.send(course);
  })
})

假设,我给名字一个值,但不给传记值。所以传记的值将是“未定义”。现在我不想在值是“未定义”的地方得到任何东西。我使用过 mongodb

https://i.stack.imgur.com/39qHH.jpg

【问题讨论】:

  • 您可以将document 添加到您的问题中吗?
  • 欢迎来到 SO!请提供一个最小的例子,说明你到目前为止尝试过的事情以及你在哪里挣扎:)
  • @AminTaghikhani 请立即查看。

标签: node.js reactjs mongodb


【解决方案1】:

javascript 中,当您想从object 访问key 并且key 不存在于object 中时,它返回undefiend

const biography = req.body.biography; // return undefiend if not exists

如果您想要null 值或default 值,而key 不存在,此代码将为您提供帮助

const biography = req.body.biography || null; // return null if not exists

const biography = req.body.biography || ''; // return empty string if not exists

【讨论】:

  • 但是为什么我不能返回一个以上的空字符串。
  • 请提供更多详细信息。
  • 例如 const biography = req.body.biography || '';常量名称 = req.body.name|| '';常量年龄= req.body.age || ''; boigraphy 的结果将是“”,但对于姓名和年龄返回“未定义”。是否可以为所有输入获得“”?
  • 是的,所有输入都可以获得'',您可以登录您的req.body 并发送给我吗?
猜你喜欢
  • 2021-03-10
  • 2020-06-29
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多