我在模型模式中同时使用了mongoose-paginate-v2和mongoose-lean-virtuals两个插件。当我使用paginate方法查询mongoDb时,我想将{ virtuals: ['stockStatus'] }
设置为lean方法。
我设置了lean:在分页选项中为true,但查询不返回我的虚拟字段。
我的API控制器:
Product.paginate({}, paginationOptions(req, 'productsList'))
.then(result => {
res.json({ message: "Products list",...result});
})
.catch (error => {
next(error);
})
exports.paginationOptions = (req, docName, isLean) => {
const options = {
lean : true,
page: req.query.page,
limit: req.query.limit,
sort: { _id: req.query.sort },
customLabels: {
totalDocs: 'itemCount',
docs: docName,
limit: 'perPage',
page: 'currentPage',
nextPage: 'next',
prevPage: 'prev',
totalPages: 'pageCount',
pagingCounter: 'slNo'
}
}
if (isLean === false ) {options.lean = false}
return (!req.query.page || !req.query.limit) ? {...options, pagination: false} : options
};
型号
const ProductSchema = new Schema({
SKU : { type: String, index: true, unique: true },
title: String,
description: String,
status: String,
brand: String,
supplier: String,
stockUnit: String,
manufacturer: String,
manufacturerReference: String
},
{
timestamps: true
})
ProductSchema.virtual('stockStatus').get(function() {
return 1
})
ProductSchema.plugin(mongooseLeanVirtuals);
ProductSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('Product', ProductSchema)
1条答案
按热度按时间mcdcgff01#
我找到了解决办法:
精益选项可以接受一个布尔值或一个对象。2要指定一个虚拟属性,只需指定
lean : { virtuals: ['stockStatus'] }