我需要查詢所有產品,但只有類別狀態為真,我的產品型號是這樣的:
const ProductSchema = Schema({
name : {type: String},
category: {type: Schema.Types.ObjectId, ref: 'Category'}
})
通常我只會進行查詢,然后對具有 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)
但遺憾的是它不起作用,有沒有辦法做到這一點還是我應該放棄?
uj5u.com熱心網友回復:
您可以通過聚合輕松實作此目的:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/440276.html
標籤:javascript 节点.js 数据库 mongodb 猫鼬
