同步数量加 1 操作
module.exports.addNumCategory = async (_id) => {
return await CategoryModel.updateOne(
{ _id },
{ $inc: { articleCount: 1 } },
)
}
分页查询操作
module.exports.getCategoryAll = async (pageNum, pageSize) => {
const list = await CategoryModel.find()
.skip((pageNum - 1) * pageSize)
.limit(pageSize)
.sort({ order: -1 })
const total = await CategoryModel.countDocuments()
return {
list,
total,
pageNum,
pageSize,
}
}
聚合查询 关联表查询
module.exports.getArticleByUser = async (pageNum, pageSize) => {
const list = await ArticleModel.aggregate([
{ $skip: (pageNum - 1) * pageSize },
{ $limit: pageSize },
{ $sort: { time_stamp: -1 } },
{
$lookup: {
from: UserModel.collection.name,
localField: 'author_uid',
foreignField: 'uid',
as: 'author_data'
}
},
{ $unwind: '$author_data' },
{
$project: {
_id: 1,
title: 1,
address: 1,
time: 1,
'author_data.nickname': 1
}
}
])
模糊查询地址 例子
module.exports.searchAddressAg = async (keyword) => {
const regex = new RegExp(keyword, 'i')
const res = await AddressModel.aggregate([
{
$match: {
$or: [
{ provinceName: regex },
{ 'citys.cityName': regex }
]
}
},
{
$project: {
_id: 0,
provinceName: 1,
citys: {
$filter: {
input: '$citys',
as: 'city',
cond: {
$or: [
{ $regexMatch: { input: '$$city.cityName', regex } },
{ $regexMatch: { input: '$provinceName', regex } }
]
}
}
}
}
}
])
return res
}
lean() 表示返回的是 普通 json 数据 只用于返回前端展示 不做操作
module.exports.getUserById = async (uid) => {
return await UserModel.find({ uid }, { _id: true }).lean()
}
联表查询的第二种方式(非聚合)
module.exports.getUserAllList = async () => {
return await UserModel.find()
.select({
_id: 0,
experience: 0,
})
.populate({
path: 'role',
select: '-createAt -updateAt -permissions -_id',
})
.lean()
}
分页查询 带关键字查询以及分类id查询
module.exports.getArticleList = async (pageNum, pageSize, keyword, category) => {
const matchCondition = {}
if (keyword) {
matchCondition.$or = [
{ title: { $regex: keyword, $options: 'i' } },
{ description: { $regex: keyword, $options: 'i' } },
]
}
if (category) {
matchCondition.category = new mongoose.Types.ObjectId(category + '')
}
const list = await ArticleModel.aggregate([
{ $match: matchCondition },
{ $skip: (pageNum - 1) * pageSize },
{ $limit: pageSize },
{ $sort: { time_stamp: -1 } },
{
$lookup: {
from: CategoryModel.collection.name,
localField: 'category',
foreignField: '_id',
as: 'category_data',
},
},
{
$unwind: '$category_data',
},
])
const total = await ArticleModel.countDocuments()
return {
list,
total,
pageNum,
pageSize,
}
}