node.js - MongoDB Aggregate 中的 Mongoose Virtuals

标签 node.js mongodb mongoose aggregation-framework

我的 Mongoose Schema 如下:

var DSchema = new mongoose.Schema({
  original_y: {type: Number},,
  new_y: {type: Number},,
  date: {type: Date},
  dummy: [dummyEmbeddedDocuments]
  }, toObject: { virtuals: true }, toJSON: { virtuals: true}
});

DSchema.virtual('dateformatted').get(function () {
 return moment(this.date).format('YYYY-MM-DD HH:mm:ss');
});

module.exports = mongoose.model('D', DSchema);

我的架构中的文档如下:

{
 id:1,
 original_y: 200,
 new_y: 140,
 date: 2015-05-03 00:00:00.000-18:30,
 dummy: [
  {id:1, storage:2, cost: 10},
  {id:2, storage:0, cost: 20},
  {id:3, storage:5, cost: 30},
  ]
}

我的查询:

Item.aggregate([
{ 
    "$match": {
        "dummy.storage": {"$gt": 0}
    } 
},
{ 
    "$unwind": "$dummy"
},
{
    "$project": {
        "original_y": 1, 
        "new_y": 1,
        "dateformatted": 1,
        "dummy.id": "$dummy.id",
        "dummy.storage": "$dummy.storage",
        "dummy.cost": "$dummy.cost",
        "dummy.tallyAmount": {
            "$divide": [
                { "$add": ["$new_y","$original_y"] },
                "$dummy.cost"
            ]
        }
    }
},
{
    "$group": {
        "_id": "_$id",
        "original_y": { "$first": "$original_y" },
        "dateformatted": { "$first": "$dateformatted" },
        "new_y": { "$first": "$new_y" },
        "dummy": {
            "$addToSet": "$dummy"
        }
    }        
}
]).exec(callback);

但是,此查询将 VIRTUAL 日期格式属性返回为 NULL。关于为什么会发生这种情况的任何想法?

最佳答案

the docs 中的一些注释谈谈为什么会这样:

  • 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.
  • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).

但它超出了这一点,因为 aggregate 操作是在服务器端执行的,在服务器端不存在任何客户端 Mongoose 概念,如虚拟。

结果是您需要在 $project$group 阶段中包含 date 字段并添加您自己的 dateformatted 字段根据 date 值生成代码。

关于node.js - MongoDB Aggregate 中的 Mongoose Virtuals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30038855/

相关文章:

javascript - 从内部回调中断父函数的执行

javascript - 如何从项目或目录自动导入 .scss 文件

mongodb - ObjectID 和字符串版本之间的唯一区别是它更小?

java - 有没有办法将 FindIterable<Document> 转换为 JSONArray 字符串?

c++ - 插入后缺少 MongoDB 记录

javascript - 在 Mongoose 模式设计中使用 new 关键字

包含 "@"的 MongoDB 密码

node.js - Node JS + Express - 将整个项目文件夹移动到同一驱动器上的不同目录

node.js - 使用 node.js、express 和 mongoose 搭建脚手架,比如 grails?

javascript - Node js( Mongoose )没有响应