Kun*_* Nk 5 mongoose mongodb node.js
在“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)
您可以使用运算符来获取数组长度为零的$size所有文档。answers
QAns.find({
answers: { $size: 0 }
})
Run Code Online (Sandbox Code Playgroud)
$size运算符用于按元素数量查询数组。
answers要选择数组不为空的所有文档,请使用$not运算符和$size运算符。
answers以下查询将选择数组不为空的所有文档
QAns.find({
answers: {
$not: { $size: 0 }
}
})
Run Code Online (Sandbox Code Playgroud)
$not运算符对指定的内容执行逻辑 NOT 运算<operator-expression>,并选择与该内容不匹配的文档<operator-expression>
PS 以上查询还将返回那些answers不存在字段的文档
| 归档时间: |
|
| 查看次数: |
3051 次 |
| 最近记录: |