Node.js 如何使用mongoose的聚合来计算文本的总长度?

Node.js 如何使用mongoose的聚合来计算文本的总长度?,node.js,mongoose,Node.js,Mongoose,我正在研究这个文本模型 const mongoose = require ('mongoose') const textSchema = new mongoose.Schema({ text : { type: String, required: true }, owner : { type: mongoose.Schema.Types.ObjectId, reuire: true, ref

我正在研究这个文本模型

const mongoose = require ('mongoose')

const textSchema = new mongoose.Schema({
    text : {
        type: String,
        required: true
    },
    owner : {
        type: mongoose.Schema.Types.ObjectId,
        reuire: true,
        ref: 'User'
    }
}, {
    timestamps: true
})

const Text = mongoose.model('Text', textSchema)

module.exports = Text
我想计算一天中文本的总长度,这是我的代码(注释中的代码是我想使用的代码,但它不起作用)

因此,我想要的是如何使用mongoose的聚合实现这一点(part注释中的问题是,
$match
中的part
createdAt
返回一个空数组)

  • $match
    您的条件
  • $strLenCP
    运算符计算指定字符串中的代码点数量
  • $group
    按null键,并获取所有文档文本的总长度

您可以这样检查条件:

if (totalTextLength.length && totalTextLength[0].totalLength > maxLimitCharPerDay) {
  return res.status(402).send({ error: 'Payment required' });
}
const totalTextLength = await Text.aggregate([
  {
    $match: {
      owner: req.user._id,
      createdAt: {
        $gte: start,
        $lte: end
      }
    }
  },
  {
    $group: {
      _id: null,
      totalLength: {
        $sum: { $strLenCP: "$text" }
      }
    }
  }
]).exec();
if (totalTextLength.length && totalTextLength[0].totalLength > maxLimitCharPerDay) {
  return res.status(402).send({ error: 'Payment required' });
}