首页 > 解决方案 > 如何使用 Node.JS 中的 Mongoose 在 MongoDB 中查找其中包含空数组的文档?

问题描述

在“QAns”模型中,我想使用 node.js 中的 mongoose 加载“Answers”字段为空数组的所有文档。我正在使用 MongoDB Atlas 来存储我的数据。这是我的数据库架构:

const QuestAnsSchema = new Schema({
    text: String,
    author: String,
    answers: [{
        text: String,
        author: String
   }]
});

这是 MongoDB 数据库中的数据。

{
     "_id":{"$oid":"5ee1f235a1e9870daca7d5e9"},
     "text":"Question 1",
     "author":"5ee1b8ebdbf91b23a808d417",
     "answers":[],
     "__v":{"$numberInt":"0"}
},
{
     "_id":{"$oid":"5ee1f235885770darrr7f449"},
     "text":"Question 2",
     "author":"5ee1b8ebdbf9o2w3a808d417",
     "answers":[],
     "__v":{"$numberInt":"0"}
}

两个文档的“答案”字段都为空,但假设有些文档的“答案”字段不为空,我将如何加载没有答案字段的文档?

我已经尝试过这段代码,但它给出了“错误请求”错误:

router.get('/questions', (req, res) => {
    QAns.find({answers: { $exists: true, $ne: [] } }).then(( err, result) => {
        if(err)  return res.sendStatus(400);

        res.render('questions',{ result });

        console.log(result);
    });

})

标签: node.jsmongodbmongoose

解决方案


您可以使用$size运算符来获取answers数组长度为零的所有文档。

QAns.find({
  answers: { $size: 0 } 
})

$size运算符用于按元素数量查询数组。

编辑:

answers要选择数组不为空的所有文档,请使用$not运算符和$size运算符。

以下查询将选择answers数组不为空的所有文档

QAns.find({
  answers: {
    $not: { $size: 0 }
  }
})

$not运算符对指定执行逻辑 NOT 操作<operator-expression>并选择不匹配的文档<operator-expression>

PS 上面的查询也将返回那些answers字段不存在的文档


推荐阅读