var expenseSchema = new Schema({
particular : String,
date : {type : Date, default: Date.now},
paid_by : String,
amount : Number
});
// your schema
var mySchema = new Schema({
name : {type: String, trim: true},
admin : {type: String, trim: true},
expense: [expenseSchema]
});
的名字
---更新:
现在这个更新expense
是没有任何月份分类的expenseSchema
的数组。然后,如果你想获得的所有费用在特定的月份,你可以简单地做一个像这样的聚合:
db.users.aggregate(
[
// this match is for search the user
{ $match: { name: "<ADMIN NAME>"} },
// this unwind all expenses of the user selected before
{ $unwind: "$expense" },
// this project the month number with the expense
{
$project: {
expense: 1,
month: {$month: '$expense.date'}
}
},
// this search all the expenses in a particular month (of the user selected before)
{ $match: { month: 8 } },
// this is optional, it's for group the result by _id of the user
//(es {_id:.., expenses: [{}, {}, ...]}. Otherwise the result is a list of expense
{
$group: {
_id:"$month",
expenses: { $addToSet: "$expense"}
}
}
]);
我可以添加一月,二月,等通过代码,而不是架构硬编码呢?就像我的意思是说只有在需要时才添加月份数组 –
nope。使用此解决方案,您只能硬编码所有月份。您无法定义将来动态更改的模型(例如添加一个月)。你可以改变你的结构或硬编码整个月,如果没有花费的阵列它是空的。检查[this](https://github.com/Automattic/mongoose/issues/1867) – gianlucatursi
有没有更好的方法来做到这一点?我需要为此文档存储每个月的费用。而费用是问题中提到的一个对象。如果你能提供一些更好的想法,那会很好。 –