当前位置 : 主页 > 网页制作 > Nodejs >

node.js – MongoDB聚合中的Mongoose虚拟

来源:互联网 收集:自由互联 发布时间:2021-06-16
我的Mongoose架构如下: 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.
我的Mongoose架构如下:

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 dateformatted属性返回为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).

但它超越了这一点,因为聚合操作是在服务器端执行的,其中任何客户端Mongoose概念(如虚拟)都不存在.

结果是您需要在$project和$group阶段中包含日期字段,并根据日期值将自己的dateformatted字段添加到代码中的结果中.

网友评论