node.js - Mongoose 聚合查询跳过 getter

标签 node.js mongodb mongoose

我有以下 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/

相关文章:

Mongoose 使用 $and 应用相同的属性两个过滤器

php - socket.io中的这段代码是什么意思

node.js - 使用请求 api (node.js) 时出现未知协议(protocol)错误

node.js - 是否可以让 nodejs 脚本监听同一个端口

angular - 如何获取新项目ngrx的id

javascript - 检查数组是否包含 mongodb 文档中的帖子 id

javascript - 使用 a+ 在 Node 中构造正确的 Promise

node.js - Mongoose upsert 不创建默认模式属性

node.js - Mongoose,无法从文档获取数据

mongodb - 如何在mongodb中分别按相应周、月、年的每一天、每一周、每一月汇总数据