node.js - 如何使用 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);
});
})
- QAns 是模型名称,answers 是数组字段
- 'questions' 是 ejs 文件,它将在加载后显示这些文档。
解决方案
您可以使用$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
字段不存在的文档
推荐阅读
- stored-procedures - 在 Synapse 中动态创建外部表
- solidity - 如何可靠地从我的合约中提取所有代币
- python - Hugginface NER 管道是否在内部处理长文档?
- jenkins - 可以从 Jenkins 共享管道库生成 json 文件,然后在 Active Choices Reactive Parameter groovy 脚本中使用它吗?
- python - 有没有比使用 .apply 和 str.contains 更快的方法来搜索数据框的每一列以查找字符串?
- azure-devops - 删除 Workitem Azure devops 中的注释
- wordpress - 添加尾部斜杠 htacess 多次重定向
- php - 如何一次开发多个 Composer 包?
- python - 在 python def 参数中传递部分数据框名称
- python - 如何在 SQLAlchemy 中获取关系列的数据?