我可以通过在 mongoose 查询中填充 属性 来获取行数吗?
Can I get rows count by populated property in mongoose query?
填充时我有如下问题对象。
{
title: "Question Title",
category: {
"_id": "562ddc95a93f89e012554be1",
"name": "Category",
"parent": {
"_id" : "562ddc95a93f89e012554be1",
"name": "Parent Category"
}
}
}
和如下类别对象
{
"_id" : "562ddc95a93f89e012554be1",
"name": "Category Name",
"parent": "562ddc95a93f89e012554be1"
}
我想获取特定父类别中的问题计数。
我尝试了这样的查询,但它不起作用。
Questions
.count("category.parent._id":_id)
我该怎么做?这在猫鼬中可能吗?
您可以像这样构造您对 count 的使用:
Questions.count({"category.parent._id" : _id}, function(err, c){
if(err) return err;
console.log('Count is ' + c);
});
查看 Docs.
中的各种可能性
为了在 mongodb shell 中对此进行测试,我在名为问题的集合中创建了以下两个文档。
{
"title" :"Question1",
"category":{
"_id":"123",
"name" : "category 1",
"parent" : {
"_id" : "567",
"name" : "parent category"
}
}
},
{
"title" :"Question2",
"category":{
"_id":"124",
"name" : "category 1",
"parent" : {
"_id" : "568",
"name" : "parent category"
}
}
}
这个查询应该 return 1:
db.questions.count({"category.parent._id":"568"})
您应该将标准放在双引号中。不使用可能会报错
填充时我有如下问题对象。
{
title: "Question Title",
category: {
"_id": "562ddc95a93f89e012554be1",
"name": "Category",
"parent": {
"_id" : "562ddc95a93f89e012554be1",
"name": "Parent Category"
}
}
}
和如下类别对象
{
"_id" : "562ddc95a93f89e012554be1",
"name": "Category Name",
"parent": "562ddc95a93f89e012554be1"
}
我想获取特定父类别中的问题计数。
我尝试了这样的查询,但它不起作用。
Questions
.count("category.parent._id":_id)
我该怎么做?这在猫鼬中可能吗?
您可以像这样构造您对 count 的使用:
Questions.count({"category.parent._id" : _id}, function(err, c){
if(err) return err;
console.log('Count is ' + c);
});
查看 Docs.
中的各种可能性为了在 mongodb shell 中对此进行测试,我在名为问题的集合中创建了以下两个文档。
{
"title" :"Question1",
"category":{
"_id":"123",
"name" : "category 1",
"parent" : {
"_id" : "567",
"name" : "parent category"
}
}
},
{
"title" :"Question2",
"category":{
"_id":"124",
"name" : "category 1",
"parent" : {
"_id" : "568",
"name" : "parent category"
}
}
}
这个查询应该 return 1:
db.questions.count({"category.parent._id":"568"})
您应该将标准放在双引号中。不使用可能会报错