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
中的partcreatedAt
返回一个空数组)
您的条件$match
运算符计算指定字符串中的代码点数量$strLenCP
按null键,并获取所有文档文本的总长度$group
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' });
}