我有以下 Mongoose 模式
var schema = new mongoose.Schema({
subtotal: {type: Number, required: true, default: 0},
owner: { type : Number, required : true, index: true},
products: [{type: mongoose.Schema.ObjectId, ref: 'Product'}],
}, {
timestamps: true
});
schema.path('subtotal').set(function(p){
return p * 100;
});
schema.path('subtotal').get(function(p){
return parseFloat((p/100).toFixed(2));
});
schema.set('toJSON', {getters: true, setters:true});
schema.set('toObject', {getters: true, setters:true});
运行简单的查找查询会按预期返回小计值(例如 11.99)。
当我运行聚合查询时,小计值并未像我预期的那样除以 100。
Order.aggregate([
{ $match: { $and: [
{status: 'COMPLETE'},
{premises: mongoose.Types.ObjectId(premisesId)},
{createdAt:{
$gte: startOfToday,
$lt: endOfToday
}}
]}},
{
$group: {
_id: {hour: {$hour: "$createdAt"}},
count: { $sum: 1 },
sales: { $sum: '$subtotal'}
}
},
{
$sort: {
"_id.hour": 1
}
}
]).exec(function(err, orders){
//do something
})
这是预期的聚合行为吗?
有没有一种方法可以强制聚合查询触发 setter/getter 。
最佳答案
简短回答:是的,这是预期的行为。
更长的答案需要引用 mongoose 的文档 Model.aggregate
:
Arguments are not cast to the model's schema because $project operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format.
本质上,这意味着 Mongoose 通过使用模式所允许的任何魔力在使用聚合(包括 setter/getter )时都不会应用。您需要将该转换包含在管道中。
关于node.js - Mongoose 聚合查询跳过 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47832584/