如何从MongoDB中查询并展示所有值不为undefined的字段内容?
实现方案
你可以通过两种路径实现需求,优先推荐从插入数据的源头处理:
方案一:插入阶段剔除空字段(推荐)
插入数据时不把值为undefined的字段写入数据库,从根源避免无效字段存储,修改新增接口代码如下:
app.post('/add_teacher',(req,res)=>{ // 仅构造存在有效值的字段对象 const insertDoc = { name: req.body.name } if(req.body.biography !== undefined) { insertDoc.biography = req.body.biography } teacherCollection.insertOne(insertDoc) .then(result =>{ console.log(result); res.send(result.insertedCount>0); }) })
这种方案下,未传biography的文档不会存在该字段,查询时自然不会返回。
方案二:查询阶段过滤undefined字段
如果已经存在存量无效数据,无法修改插入逻辑,可以在查询时通过MongoDB聚合的$$REMOVE系统变量移除值为undefined的字段,修改查询接口代码如下:
app.get('/get_all_teacher', (req, res) =>{ teacherCollection.aggregate([ { $project: { // 保留_id、name字段 _id: 1, name: 1, biography: { $cond: { // 字段值不等于undefined才返回,否则移除该字段 if: { $ne: ["$biography", undefined] }, then: "$biography", else: "$$REMOVE" } } } } ]).toArray((err, teachers) =>{ res.send(teachers); }) })
内容的提问来源于stack exchange,提问作者Apurbo Kumar Paul
相关产品推荐
相关产品推荐

