mongodb mongoose-paginate-v2 + mongoose-lean-virtuals:如何为精益方法设置虚拟参数

oknwwptz  于 2023-03-29  发布在  Go
关注(0)|答案(1)|浏览(180)

我在模型模式中同时使用了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)
mcdcgff0

mcdcgff01#

我找到了解决办法:
精益选项可以接受一个布尔值或一个对象。2要指定一个虚拟属性,只需指定lean : { virtuals: ['stockStatus'] }

相关问题