小编Kun*_* Nk的帖子

如何使用 Node.JS 中的 Mongoose 查找 MongoDB 中包含空数组的文档?

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

const QuestAnsSchema = new Schema({
    text: String,
    author: String,
    answers: [{
        text: String,
        author: String
   }]
});
Run Code Online (Sandbox Code Playgroud)

这是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"}
}
Run Code Online (Sandbox Code Playgroud)

这两个文档中的“答案”字段都是空的,但假设有一些文档具有非空的“答案”字段,我将如何加载没有答案字段的文档?

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

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);
    });

})
Run Code Online (Sandbox Code Playgroud)
  • QAns 是模型名称,answers 是数组字段
  • “questions”是 ejs 文件,它将在加载这些文档后显示这些文档。

mongoose mongodb node.js

5
推荐指数
1
解决办法
3051
查看次数

标签 统计

mongodb ×1

mongoose ×1

node.js ×1