有没有办法用猫鼬过滤这个请求?
Is there a way to filter this request with mongoose?
我需要查询所有产品,但只有类别状态为 true,
我的产品型号是这样的:
const ProductSchema = Schema({
name : {type: String},
category: {type: Schema.Types.ObjectId, ref: 'Category'}
})
通常我只会进行查询,然后对具有类别的产品进行筛选。
status === true
,但问题是我正在使用分页,由于过滤器,我的 15 个产品页面最终的产品数量明显少于 15 个,显然是因为过滤器,所以我真的不知道我是否可以在查询中使用人口进行过滤,也许是这样的:
const query = await Product.find().populate('category', 'name status')
.select(['-cost']).where('category.status')
.equals(true).skip(0).limit(15)
但遗憾的是它不起作用,有什么办法可以做到还是我应该放弃?
您可以通过聚合轻松实现此目的:
const query = await Product.aggregate([
{
$lookup: {
from: 'Category',
localField: 'category',
foreignField: '_id',
as: 'status'
}
},
{
$match: {
"status.status": true
}
},
{
$project: {
"cost": 0, // disclude
}
},
{
$limit: 15
},
{
$skip: 0
}
])
// passed the tests in my database
我需要查询所有产品,但只有类别状态为 true,
我的产品型号是这样的:
const ProductSchema = Schema({
name : {type: String},
category: {type: Schema.Types.ObjectId, ref: 'Category'}
})
通常我只会进行查询,然后对具有类别的产品进行筛选。
status === true
,但问题是我正在使用分页,由于过滤器,我的 15 个产品页面最终的产品数量明显少于 15 个,显然是因为过滤器,所以我真的不知道我是否可以在查询中使用人口进行过滤,也许是这样的:
const query = await Product.find().populate('category', 'name status')
.select(['-cost']).where('category.status')
.equals(true).skip(0).limit(15)
但遗憾的是它不起作用,有什么办法可以做到还是我应该放弃?
您可以通过聚合轻松实现此目的:
const query = await Product.aggregate([
{
$lookup: {
from: 'Category',
localField: 'category',
foreignField: '_id',
as: 'status'
}
},
{
$match: {
"status.status": true
}
},
{
$project: {
"cost": 0, // disclude
}
},
{
$limit: 15
},
{
$skip: 0
}
])
// passed the tests in my database