gpt4 book ai didi

node.js - MongoDB Aggregate 中的 Mongoose Virtuals

转载 作者:IT老高 更新时间:2023-10-28 12:28:57 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com